⚡️ Speed up method LQ.stationary_values
by 13%
#17
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.
📄 13% (0.13x) speedup for
LQ.stationary_values
inquantecon/_lqcontrol.py
⏱️ Runtime :
12.2 seconds
→10.9 seconds
(best of5
runs)📝 Explanation and details
The optimized code achieves a 12% speedup by eliminating redundant computations and caching intermediate results in the
solve_discrete_riccati
function, which dominates 98.9% of the runtime.Key Optimizations:
Caching of gamma initialization data: Instead of recomputing
Q_tilde
,G0
,A0
,H0
for the selected gamma after the candidate loop, these values are now cached ingamma_data_cache
during the selection process and reused directly. This eliminates expensive matrix operations and linear solves that were being repeated.Precomputed solve operations in main loop: The iterative doubling algorithm now precomputes shared solve operations (
solve_IGH_A0
,solve_IHG_A0T
,solve_IHG_HA0
) to avoid redundant linear system solves within each iteration.Minor optimization in
stationary_values
: Thenp.sqrt(self.beta)
computation is cached assqrt_beta
to avoid computing it twice.Performance Impact by Test Case:
The optimizations are most effective for cases requiring multiple iterations in the doubling algorithm, where the caching of solve operations provides cumulative benefits. The consistent speedup across different matrix conditions shows the optimizations are robust and don't introduce numerical instability.
✅ Correctness verification report:
⚙️ Existing Unit Tests and Runtime
test_lqnash.py::TestLQNash.test_noninteractive
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-LQ.stationary_values-mggx6r22
and push.