Speed up function _negotiate_grid_size by 338%
          #1670
        
          
      
  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.
  
    
  
    
📄 338% (3.38x) speedup for
_negotiate_grid_sizeininference/core/utils/drawing.pySaurabh's comments: Speeds up creation of tiles, which seems to be a core drawing operation
⏱️ Runtime :
251 microseconds→57.3 microseconds(best of338runs)📝 Explanation and details
The optimization achieves a 338% speedup by replacing expensive operations with more efficient alternatives and eliminating loops:
Key optimizations:
Replace
math.ceil(np.sqrt())withmath.isqrt(): The original code used NumPy's square root followed by math ceiling, which is computationally expensive. The optimized version uses Python'smath.isqrt()for efficient integer square root calculation, then adds 1 only when needed for non-perfect squares.Eliminate the while loop: Instead of iteratively decrementing
proposed_rowsuntil the grid fits, the optimized code directly calculates the required rows using ceiling division:(images_len + proposed_columns - 1) // proposed_columns. This removes the need for multiple iterations and condition checks.Cache
len(images): Store the length inimages_lenvariable to avoid repeated function calls.Performance impact by test case:
np.sqrt()+math.ceil()combination and the iterative loopmath.isqrt()efficiencyThe optimization is most effective for the common case where images need to be arranged in a multi-row grid, transforming an O(sqrt(n)) iterative process into O(1) direct calculation.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-_negotiate_grid_size-mh2mp7zgand push.