⚡️ Speed up function mean by 22%
#282
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.
📄 22% (0.22x) speedup for
meaninpandas/core/array_algos/masked_reductions.py⏱️ Runtime :
1.92 milliseconds→1.57 milliseconds(best of83runs)📝 Explanation and details
The optimized code achieves a 22% speedup by adding a crucial fast-path optimization that eliminates redundant work for arrays with no missing values.
Key optimization: Early exit for mask.any() == False
The primary improvement is adding a fast-path check
if not mask.any():at the beginning. When there are no masked values (a very common case), the optimized code:func(values, axis=axis, **kwargs)after checking min_countwhere=~maskparameter in numpy operationsWhy this matters:
where=~maskeven when no values were masked, forcing numpy to process the mask unnecessarilyreturn func(values, where=~mask, axis=axis, **kwargs)line took 84% of execution time in the original vs only 47.3% in the optimized versionPerformance characteristics:
The optimization is particularly effective because
mask.any()is a highly optimized numpy operation that can short-circuit, making the additional check very cheap compared to the avoidedwhereparameter overhead.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-mean-mho7wi26and push.