⚡️ Speed up function zsqrt by 7%
#403
Open
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.
📄 7% (0.07x) speedup for
zsqrtinpandas/core/window/common.py⏱️ Runtime :
6.71 milliseconds→6.25 milliseconds(best of43runs)📝 Explanation and details
The optimization replaces direct mask-based assignment (
result[mask] = 0) with vectorized conditional operations. For DataFrames, it usesresult.where(~mask, other=0)and for arrays, it usesnp.where(mask, 0, result).Key Performance Improvements:
Vectorized operations: Both
whereandnp.whereare implemented in C and optimized for element-wise operations, avoiding Python loop overhead that can occur with direct assignment on masked arrays.Memory efficiency: The
whereoperations create new arrays more efficiently than in-place assignment, which can trigger additional memory allocations and copying in pandas DataFrames.DataFrame optimization: The original
result[mask] = 0on DataFrames is particularly slow (706μs per hit in the profiler) because it involves pandas indexing machinery. The optimizedresult.where(~mask, other=0)reduces this to 603μs per hit, a 14% improvement on the hottest line.Function Usage Context:
The
zsqrtfunction is called in exponentially weighted moving window calculations for computing standard deviation and correlation inpandas/core/window/ewm.py. These are common statistical operations that may be called repeatedly in financial analysis or time series processing, making the 7% overall speedup meaningful.Test Case Performance:
The optimization shows consistent improvements on DataFrame operations (8-11% faster for most DataFrame tests) while showing mixed results on simple arrays. The largest gains are seen in DataFrame-heavy workloads, which aligns with the function's usage in EWM calculations that typically operate on DataFrame columns.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-zsqrt-miy5i2oeand push.