⚡️ Speed up function calculate_smoothed_npmi by 19%
#169
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.
📄 19% (0.19x) speedup for
calculate_smoothed_npmiinmlflow/store/analytics/trace_correlation.py⏱️ Runtime :
226 microseconds→190 microseconds(best of91runs)📝 Explanation and details
The optimized code achieves a 19% speedup through several micro-optimizations that reduce function call overhead and improve computational efficiency:
Key optimizations in
_calculate_npmi_core:log = math.logeliminates repeated attribute lookups tomath.log, creating a faster local reference-(log_n11 - log_N)tolog_N - log_n11to avoid the negation operationmax(-1.0, min(1.0, npmi))with explicit conditional checks, eliminating two function calls and their associated overheadKey optimization in
calculate_smoothed_npmi:min(n11, n10, n01, n00) < 0withn11 < 0 or n10 < 0 or n01 < 0 or n00 < 0, avoiding tuple creation and themin()function callsmoothing: float = 0.5directly instead of referencingJEFFREYS_PRIOR, eliminating a module-level attribute lookupPerformance impact by test case:
These optimizations are particularly effective because they target the most frequently executed code paths in statistical calculations, where even small reductions in overhead compound significantly across many invocations.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-calculate_smoothed_npmi-mhx22r5pand push.