⚡️ Speed up function correlation
by 37,073%
#102
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.
📄 37,073% (370.73x) speedup for
correlation
insrc/numpy_pandas/dataframe_operations.py
⏱️ Runtime :
891 milliseconds
→2.40 milliseconds
(best of779
runs)📝 Explanation and details
The optimized code achieves a 371x speedup by eliminating the most expensive operations in the original implementation:
Key Optimizations:
Vectorized Data Access: Instead of using
df.iloc[k][col]
in nested loops (which accounted for 99.4% of runtime), the code converts each column to NumPy arrays once usingdf[col].to_numpy()
. This eliminates 46,000+ expensive pandas indexing operations per correlation pair.Vectorized NaN Filtering: Replaces the row-by-row
pd.isna()
checks and list appending with a single vectorized mask operation~np.isnan(arr_i) & ~np.isnan(arr_j)
, then uses boolean indexingarr_i[mask]
to select valid values.Vectorized Statistics: All statistical calculations (mean, variance, covariance) now use NumPy's vectorized operations like
.mean()
and broadcasting instead of Python loops withsum()
and list comprehensions.Performance Impact by Test Case:
The optimization is most effective for larger datasets where the original's nested loops with pandas indexing created severe performance bottlenecks. The vectorized approach scales linearly with data size rather than quadratically.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-correlation-mfekr48s
and push.