⚡️ Speed up method LQMarkov.stationary_values by 16%
#18
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.
📄 16% (0.16x) speedup for
LQMarkov.stationary_valuesinquantecon/_lqcontrol.py⏱️ Runtime :
12.6 seconds→10.9 seconds(best of5runs)📝 Explanation and details
The optimized code achieves a 15% speedup through several key optimizations focused on reducing memory allocations and improving computational efficiency:
Matrix Buffer Optimizations:
np.copy(Ps)withnp.empty_like(Ps)to avoid unnecessary copyingPs, Ps1 = Ps1, Ps) instead of expensive array copying operations.fill(0.0)instead of slice assignment for zeroing arrays, which is more efficientPrecomputation and Vectorization:
Bs_T,As_T,Ns_T) to avoid repeated transpose operations in inner loopspij_Bs = pij @ Bs[i]Improved Linear Algebra:
lu_factor/lu_solve) instead of directsolve()calls for better numerical stability and potential reuseMemory Management:
The optimizations are particularly effective for larger systems (50+ Markov states show 16.9% speedup) and medium-scale problems (10 states/10 dimensions show 8.11% speedup), where the reduced memory overhead and vectorization benefits compound. For very small systems, some optimizations introduce slight overhead due to additional setup costs, but the overall trend favors larger, more computationally intensive problems.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-LQMarkov.stationary_values-mggxz774and push.