⚡️ Speed up function zsqrt by 115%
#414
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.
📄 115% (1.15x) speedup for
zsqrtinpandas/core/window/common.py⏱️ Runtime :
4.90 milliseconds→2.28 milliseconds(best of27runs)📝 Explanation and details
The optimization achieves a 114% speedup by changing how the function handles DataFrame assignments when negative values need to be zeroed out.
Key optimization: For DataFrames, instead of using
result[mask] = 0which triggers pandas' indexing machinery, the code now usesresult._values[mask._values] = 0to directly modify the underlying NumPy array.Why this is faster: When assigning to a DataFrame using boolean indexing (
result[mask] = 0), pandas invokes complex logic including copy-on-write checks, index alignment, and dtype validation. By accessing the underlying NumPy array directly via._values, the assignment bypasses all this overhead and operates at the raw array level, which is much faster.Impact on workloads: Based on the function references,
zsqrtis called in hot paths within pandas' exponentially weighted moving window calculations - specifically instd()andcorr()methods that are likely to be used repeatedly on large datasets. The test results show the optimization provides dramatic speedups for DataFrame operations (200%+ faster in many cases) while having minimal impact on regular NumPy arrays.Test case performance: The optimization particularly excels with DataFrame inputs, showing 200-228% speedups in tests with mixed values, all negatives, and NaN/Inf data. NumPy array operations show smaller but consistent improvements, with edge cases and large arrays benefiting modestly (0.5-4% faster).
The change preserves all existing behavior and error handling while dramatically improving performance for the DataFrame code path.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-zsqrt-mja7v3a0and push.