⚡️ Speed up method ThresholdPruner.prune by 57%
#33
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.
📄 57% (0.57x) speedup for
ThresholdPruner.pruneinoptuna/pruners/_threshold.py⏱️ Runtime :
402 microseconds→255 microseconds(best of296runs)📝 Explanation and details
The optimization replaces
functools.reducewith a simple for-loop in the_is_first_in_interval_stepfunction to find the second-largest step value.Key Change:
functools.reducewith a lambda function to iterate throughintermediate_stepsWhy This is Faster:
The
functools.reduceapproach creates significant overhead because:s if s > second_last_step and s != step else second_last_stepis evaluated as an expression rather than a simple if-statementreducehas additional layers of abstraction compared to a direct loopThe for-loop eliminates this overhead by using:
Performance Impact:
The optimization shows 57% speedup overall, with particularly strong gains in test cases with larger intermediate step collections (up to 111% faster in some large-scale tests). The improvement is most pronounced when
intermediate_stepscontains many elements, as the per-iteration overhead reduction compounds across all iterations.Best Use Cases:
This optimization performs especially well for trials with many intermediate steps (large-scale tests show 58-62% improvements), making it ideal for long-running optimization tasks with frequent pruning checks.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-ThresholdPruner.prune-mhaze4cmand push.