⚡️ Speed up function _get_timeline_plot by 10%
#143
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.
📄 10% (0.10x) speedup for
_get_timeline_plotinoptuna/visualization/matplotlib/_timeline.py⏱️ Runtime :
517 milliseconds→471 milliseconds(best of5runs)📝 Explanation and details
The optimization replaces an inefficient nested loop with a more efficient set-based lookup for legend construction.
Key Change:
_cm, the code usedany(_get_state_name(b) == state_name for b in info.bars)- this creates a nested O(n*k) loop where n is the number of bars and k is the number of possible states (6).present_state_names = set(_get_state_name(b) for b in info.bars)once, then usesif state_name in present_state_namesfor O(1) lookups.Why This is Faster:
The original approach has O(n*k) complexity because for each of the 6 possible states, it potentially scans through all n bars to check if that state exists. With the optimization, we scan the bars once to build a set (O(n)), then do 6 constant-time set lookups (O(k)), resulting in O(n+k) total complexity.
Performance Impact:
The line profiler shows the legend check (
if any(_get_state_name(b) == state_name for b in info.bars)) took 31.6ms in the original vs the set-based approach taking only 6.5ms + 0.04ms = 6.54ms total - a ~79% reduction in that specific operation.Best For:
This optimization is particularly effective for test cases with many trials (like the 999-trial test showing 9.6% speedup) where the nested loop penalty becomes significant, while still providing consistent 8-11% improvements across all test scenarios.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-_get_timeline_plot-mhjm20ztand push.