⚡️ Speed up function std by 14%
#89
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.
📄 14% (0.14x) speedup for
stdinpandas/core/array_algos/masked_reductions.py⏱️ Runtime :
3.96 milliseconds→3.46 milliseconds(best of172runs)📝 Explanation and details
The optimized code achieves a 14% speedup through three key optimizations that reduce unnecessary computations when masks have no missing values:
1. Early mask.any() checks in _reductions()
mask.any()checks before expensive operations to avoid work when all values are validvalues[~mask]) and creating inverted masks (~mask) in thewhere=parametertest_std_basic_no_missing,test_std_large_array_no_missing)2. Fast path in std() function
if not mask.any(): return np.std(values, axis=axis, ddof=ddof)before expensive warning handlingwarnings.catch_warnings()context manager and_reductions()call when no masking is needed3. Object dtype optimization
mask.any()before array slicing to avoid creating new arrays when unnecessaryvalues[~mask]when all values are valid, using original array directlyThe optimizations are most effective for arrays with no or few missing values, which are common in real-world data. Arrays with many missing values show smaller improvements (or slight regressions due to additional checks), but the overall performance gain comes from optimizing the common case of clean data.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-std-mhbksx6nand push.