⚡️ Speed up function qnwlogn
by 6%
#14
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.
📄 6% (0.06x) speedup for
qnwlogn
inquantecon/quad.py
⏱️ Runtime :
2.91 milliseconds
→2.75 milliseconds
(best of110
runs)📝 Explanation and details
The optimized code achieves a 5% speedup through several focused micro-optimizations that reduce redundant operations and improve error handling efficiency:
Key Optimizations:
Upfront input validation with early error detection: The optimized version caches boolean checks (
mu_is_none
,sig2_is_none
) and validates array dimensions immediately after conversion, catching shape errors before expensive operations. This eliminates redundant.reshape()
calls and provides faster failure paths for invalid inputs (shown in tests with 44-2007% speedup for error cases).Eliminated temporary tuple allocation: Instead of creating temporary
_1d = _qnwnorm1(n[i])
tuples in the loop, the code directly unpacks intonode, weight = _qnwnorm1(n[i])
, reducing memory allocation overhead during the expensive_qnwnorm1
calls that dominate runtime (99.5% of execution time).Conditional addition with zero-check optimization: The code splits the matrix multiplication and addition operations, using
if mu.any()
to skip unnecessary addition whenmu
contains all zeros (common with default parameters). This avoids creating temporary arrays for zero additions.Precomputed scalar checks: Boolean flags (
n_is_scalar
,mu_is_scalar
,sig2_is_scalar
) are computed once upfront rather than being evaluated in the conditional, reducing repeated.size
attribute access.Performance Impact:
mu=0
is commonqnwnorm
is called repeatedly with similar parameter patternsThe changes maintain identical mathematical behavior while reducing Python object creation overhead and redundant array operations.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-qnwlogn-mggudvjn
and push.