⚡️ Speed up function setp by 62%
#250
Open
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.
📄 62% (0.62x) speedup for
setpinlib/matplotlib/pyplot.py⏱️ Runtime :
7.48 milliseconds→4.62 milliseconds(best of5runs)📝 Explanation and details
The optimized code achieves a 61% speedup by replacing the recursive
cbook.flattencalls with a custom_flatten_fastfunction that uses an iterative stack-based approach.Key optimization changes:
Custom iterative flattening: The new
_flatten_fastfunction eliminates recursion overhead by using a stack-based iteration. This avoids the function call overhead and stack frame creation that comes with the recursivecbook.flattenimplementation.Two critical flatten replacements:
objs = list(cbook.flatten(obj))→objs = list(_flatten_fast(obj))return list(cbook.flatten(ret))→return list(_flatten_fast(ret))Why this optimization works:
Impact on workloads:
The function reference shows
setpis called frommatplotlib.pyplot, making it part of the public plotting API. The test results demonstrate the optimization is particularly effective for:This optimization significantly benefits matplotlib users who work with many plot objects simultaneously, such as creating complex visualizations with hundreds of lines, points, or other artists that need property updates.
✅ Correctness verification report:
⚙️ Existing Unit Tests and Runtime
test_artist.py::test_setptest_polar.py::test_polar_gridlinestest_table.py::test_table_cellstest_ticker.py::test_remove_overlap🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-setp-mjacw83eand push.