⚡️ Speed up function pytest_sessionfinish by 125%
#70
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
📄 125% (1.25x) speedup for
pytest_sessionfinishinsrc/_pytest/tmpdir.py⏱️ Runtime :
38.6 milliseconds→17.2 milliseconds(best of87runs)📝 Explanation and details
The optimization replaces the expensive
left_dir.resolve().exists()check with a more efficientleft_dir.stat()call wrapped in a try-except block to detect dead symlinks.Key optimization in
cleanup_dead_symlinks:if not left_dir.resolve().exists()- This calls.resolve()which follows the symlink to its target, then.exists()to check if that target exists. For dead symlinks,.resolve()can be expensive as it tries to traverse non-existent paths.try: left_dir.stat() except FileNotFoundError:- This directly attempts to stat the symlink target. If the target doesn't exist, it raisesFileNotFoundError, which we catch to identify dead symlinks.Why this is faster:
The line profiler shows the critical bottleneck was line
if not left_dir.resolve().exists()taking 75.7% of total time (76.4ms) in the original version. The optimized version reduces this to just 16.6% (4.85ms) for theleft_dir.stat()call, delivering a 3.7x speedup in the core symlink detection logic.Performance impact by test case:
The optimization is particularly effective for workloads with many dead symlinks, as evidenced by the
test_large_number_of_files_and_symlinkscase improving from 17.5ms to 5.39ms (225% faster). Since this function is called during pytest session cleanup, the improvement reduces test suite teardown time, especially in environments with many temporary symlinks.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-pytest_sessionfinish-mi9jubn0and push.