⚡️ Speed up function generate_crop_boxes by 71%
#47
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.
📄 71% (0.71x) speedup for
generate_crop_boxesinultralytics/models/sam/amg.py⏱️ Runtime :
1.16 milliseconds→679 microseconds(best of250runs)📝 Explanation and details
The optimized code achieves a 71% speedup through several key micro-optimizations that reduce overhead in the inner loops:
Key Optimizations:
Eliminated repeated attribute lookups: Stored
crop_boxes.appendandlayer_idxs.appendin local variables (add,add_idx) to avoid repeated dot notation lookups in the tight inner loop that executes 4,764 times.Precomputed bounds checking: Moved
min()operations outside the inner loop by precomputingx1 = x0 + crop_wand using conditional assignmentx1_clipped = x1 if x1 <= min_add_crop_w else min_add_crop_w, replacing expensive function calls with simple comparisons.Reduced list comprehension overhead: Converted list comprehensions for
crop_box_x0andcrop_box_y0to tuple generator expressions, avoiding temporary list allocations while maintaining the same iteration behavior.Hoisted invariant computations: Moved loop-invariant calculations like
box_layer = i_layer + 1outside the inner loops to avoid redundant arithmetic.Performance Impact:
The optimizations are most effective for large-scale test cases where the inner loop executes many times:
Context Relevance:
Based on the function reference,
generate_crop_boxesis called in SAM'sgenerate()method for image segmentation, where it processes multiple crop regions for each input image. The optimization directly benefits this hot path by reducing the overhead of generating potentially hundreds of crop boxes per image, making real-time segmentation more efficient.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-generate_crop_boxes-mirbh0uvand push.