⚡️ Speed up function quadrect by 318%
#49
+80
−28
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.
📄 318% (3.18x) speedup for
quadrectinquantecon/quad.py⏱️ Runtime :
14.8 milliseconds→3.53 milliseconds(best of24runs)📝 Explanation and details
The optimized code achieves a 318% speedup by targeting the
qnwequifunction bottlenecks with Numba JIT compilation and caching optimizations:Key Optimizations:
Numba JIT compilation for computational hotspots: Added
@njithelper functions (_njit_prod,_njit_broadcast_repeat,_njit_arange_int64,_outer_and_subtract_fix) that replace slow pure Python operations with compiled code. The line profiler shows these operations taking 140-180ms in the original vs much faster execution in the optimized version.Optimized outer product and fix operations: The original code used
np.outer(i, j)followed by(nodes - fix(nodes))which creates large intermediate arrays. The new_outer_and_subtract_fixfunctions compute the result directly in a single pass, avoiding memory allocation overhead.Global caching for prime calculations: Added module-level caching for
equidist_ppcomputation that avoids expensive sympy prime generation on repeated calls. The line profiler shows sympy import/computation taking ~380ms originally but only ~255ms in optimized version due to caching.Efficient array broadcasting: Replaced
np.repeatcalls with the optimized_njit_broadcast_repeatfunction that handles the common case of broadcasting scalars to arrays more efficiently.Performance Impact by Test Case:
_make_multidim_funcpathFunction Usage Context: Based on the test references,
quadrectis used extensively in quantitative economics for numerical integration across multiple quadrature methods and dimensions. The optimizations particularly benefit Monte Carlo and equidistributed sequence methods that are commonly used for high-dimensional integration problems in economics and finance applications.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-quadrect-mj9z20v1and push.