⚡️ Speed up method LQMarkov.stationary_values by 670%
#53
+74
−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.
📄 670% (6.70x) speedup for
LQMarkov.stationary_valuesinquantecon/_lqcontrol.py⏱️ Runtime :
8.77 seconds→1.14 seconds(best of5runs)📝 Explanation and details
The optimization achieves a 669% speedup by leveraging Numba's JIT compilation to accelerate the computationally intensive Riccati equation solver.
Key Optimization Applied:
solve_discrete_riccati_systemwas extracted into a separate_riccati_corefunction and decorated with@njit(cache=True). This compiles the Python code to optimized machine code, eliminating Python interpreter overhead.Why This Works:
The original code spent 99.1% of its time (16.98s out of 18.02s) in the Riccati system solver, which contains:
These operations are ideal for JIT compilation because they're numerically intensive, repetitive, and have predictable data types. Numba eliminates Python's dynamic dispatch overhead and generates vectorized machine code.
Implementation Details:
np.ascontiguousarrayto ensure optimal memory access patterns for the JIT-compiled codeNoneon convergence failure, checked by the wrapper functionPerformance Impact:
The test results show consistent 400-900% speedups across different problem sizes, with larger improvements for bigger systems (e.g., 963% for 100 Markov states). This makes the optimization particularly valuable for:
The optimization preserves all mathematical behavior and API compatibility while dramatically reducing computational time for this performance-critical numerical routine.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-LQMarkov.stationary_values-mja0us90and push.