⚡️ Speed up function mlinspace by 11%
#48
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.
📄 11% (0.11x) speedup for
mlinspaceinquantecon/_gridtools.py⏱️ Runtime :
766 microseconds→693 microseconds(best of197runs)📝 Explanation and details
The optimization introduces a Numba-compiled implementation of the cartesian product calculation, achieving a 10% speedup. Here's what drives the performance improvement:
Key Optimization: Numba JIT Compilation
The core change is extracting the repetition calculation logic into
_cartesian_numba(), a function decorated with@njit(cache=True). This compiles the Python code to native machine code, eliminating Python interpreter overhead for the computational hot path.Specific Performance Improvements:
Efficient Repetition Calculation: The original code uses
np.cumprod()on Python lists and performs list operations like.reverse()and.tolist(). The optimized version replaces this with manual loops that compute cumulative products directly in Numba, avoiding expensive NumPy array creation and Python list manipulations.Memory Layout Optimization: Converting
shapesto a tuple andnodesto a tuple of arrays ensures better memory locality and reduces Python object overhead when passed to the Numba function.Compilation Caching: The
cache=Trueparameter means the compiled function is cached to disk, so subsequent calls avoid recompilation overhead.Impact Analysis:
Based on the function references, this optimization benefits grid generation in quantitative economics applications where
mlinspaceandcartesianare used to create parameter grids for numerical analysis. The test results show consistent 5-19% improvements across various grid sizes and dimensions, with larger gains for:The optimization maintains full backward compatibility while providing meaningful speedups for computational workloads that frequently generate Cartesian product grids, which is common in economic modeling and numerical optimization scenarios.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-mlinspace-mj9wn7wiand push.