⚡️ Speed up function _negotiate_grid_size by 328%
#788
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.
📄 328% (3.28x) speedup for
_negotiate_grid_sizeininference/core/utils/drawing.py⏱️ Runtime :
452 microseconds→106 microseconds(best of41runs)📝 Explanation and details
The optimized code achieves a 327% speedup through three key optimizations:
1. Replaced
np.sqrt()withmath.sqrt()The original code used
math.ceil(np.sqrt(len(images)))which is significantly slower thanmath.ceil(math.sqrt(images_len)). NumPy's sqrt function has overhead for dtype checking and array operations even when called on a scalar, whilemath.sqrt()is optimized for scalar operations.2. Eliminated the while loop with direct arithmetic
The original code used an iterative approach to find the minimum number of rows:
This was replaced with a direct calculation using ceiling division:
This eliminates 1-39 loop iterations (averaging ~0.36 iterations per call based on profiler data).
3. Cached
len(images)inimages_lenThe original code called
len(images)multiple times (3-4 times per function call). Caching this value eliminates redundant length calculations.Performance Impact Analysis:
np.sqrt()and loop operations_establish_grid_size()which handles grid layout calculations, suggesting this optimization will benefit any drawing/visualization workflows that need to arrange multiple images in gridsTest Case Insights:
The optimization is most effective for cases requiring grid calculations (4+ images), which represents the majority of real-world usage where multiple images need to be arranged in a grid layout.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-_negotiate_grid_size-miqmfhetand push.