⚡️ Speed up function _set_cmap by 4,516%
#162
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.
📄 4,516% (45.16x) speedup for
_set_cmapinoptuna/visualization/matplotlib/_contour.py⏱️ Runtime :
26.7 milliseconds→579 microseconds(best of250runs)📝 Explanation and details
The optimization pre-computes the colormap objects at module level instead of calling
plt.get_cmap()on every function invocation.Key changes:
_blues_r_cmapand_blues_cmapthat cache the colormap objectsplt.get_cmap(cmap)call with direct object referencesWhy this speeds up the code:
The line profiler shows that
plt.get_cmap(cmap)was consuming 97.2% of the function's runtime (40.88ms out of 42.04ms total). This call involves matplotlib's internal colormap lookup and object creation/retrieval mechanisms, which are expensive operations. By pre-computing these objects once at import time and storing them as module constants, we eliminate this overhead entirely on each function call.Performance impact:
test_set_cmap_many_calls_performance,test_set_cmap_with_varied_inputs) show particularly strong gains (52x speedup), indicating this optimization scales well with high call frequencyWorkload benefits:
This optimization is especially valuable for visualization code that generates multiple plots or updates plots frequently, as colormap selection is typically called repeatedly during rendering operations. The consistent speedup across all test cases suggests any workload calling this function will benefit significantly.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-_set_cmap-mhoaygqjand push.