⚡️ Speed up function is_anyio_cancellation by 25%
#2
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.
📄 25% (0.25x) speedup for
is_anyio_cancellationinsrc/anyio/_backends/_asyncio.py⏱️ Runtime :
553 microseconds→443 microseconds(best of74runs)📝 Explanation and details
The optimized code achieves a 24% speedup by eliminating redundant attribute lookups within the while loop.
Key optimizations:
Reduced attribute access: The original code repeatedly accessed
exc.args,exc.args[0], andexc.__context__multiple times per iteration. The optimized version stores these in local variables (args,context) to avoid repeated property lookups.Single variable tracking: Instead of reassigning the
excparameter directly, the optimized code uses a separatecurrentvariable to track the exception being examined, making the control flow clearer.Streamlined condition logic: The nested if-statement structure is flattened into more direct checks, reducing the overhead of multiple condition evaluations.
Why this matters for Python performance:
obj.attr) involves dictionary lookups in Python, which are relatively expensive when done repeatedlyPerformance characteristics:
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
🔎 Concolic Coverage Tests and Runtime
codeflash_concolic_tgs86_zb/tmpvh8ytz_g/test_concolic_coverage.py::test_is_anyio_cancellationTo edit these changes
git checkout codeflash/optimize-is_anyio_cancellation-mhfnn0fsand push.