⚡️ Speed up function solve_discrete_riccati_system
by 30%
#4
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.
📄 30% (0.30x) speedup for
solve_discrete_riccati_system
inquantecon/_matrix_eqn.py
⏱️ Runtime :
4.19 seconds
→3.22 seconds
(best of5
runs)📝 Explanation and details
The optimized code achieves a 30% speedup through strategic precomputation and memory optimization in the computationally intensive nested loops.
Key Optimizations:
Precompute matrix transposes:
As_T
,Bs_T
, andNs_T
are computed once upfront instead of repeatedly calling.T
in the hot loops. The profiler shows the original code spent significant time on transpose operations within the inner loops.Replace array slicing with
.fill()
: Changedsum1[:, :] = 0.
tosum1.fill(0.)
, which is more efficient for zeroing arrays and avoids creating temporary objects.Hoist loop-invariant calculations: Variables like
A_T
,B
,B_T
,R
,Q
,N
,N_T
are extracted once per outer loop iteration rather than being repeatedly accessed from arrays.Precompute reusable matrix products: In the inner loop, intermediate results like
A_T_Pj
,B_T_Pj
,A_T_Pj_B
, etc. are computed once and reused multiple times, eliminating redundant matrix multiplications.Memory allocation optimization: Use
np.empty_like(Ps)
instead ofnp.copy(Ps)
forPs1
, and preallocatesum1
/sum2
arrays outside the main loop.Performance Impact by Test Case:
The optimizations are most effective for systems with many Markov states where the nested loops execute frequently, making the precomputation overhead worthwhile.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-solve_discrete_riccati_system-mgfzy5nb
and push.