⚡️ Speed up function KMR_Markov_matrix_sequential
by 194%
#16
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.
📄 194% (1.94x) speedup for
KMR_Markov_matrix_sequential
inquantecon/markov/tests/test_core.py
⏱️ Runtime :
8.62 milliseconds
→2.93 milliseconds
(best of214
runs)📝 Explanation and details
The optimized code achieves a 194% speedup by replacing the scalar loop-based computation with vectorized NumPy operations. Here are the key optimizations:
1. Loop Elimination and Vectorization
for
loop iterating 7,271 times (for N=999), performing scalar operations on each iteration2. Precomputed Constants
epsilon * (1/2)
,1 - epsilon
, andfloat(N)
outside the loop3. Vectorized Conditional Logic
((n-1)/(N-1) < p)
and((n-1)/(N-1) == p)
evaluated per iterationcond_left
,cond_eq_left
, etc., to evaluate all conditions at once.astype(float)
4. Batch Array Operations
idx
,idx_float
) once and performs all fraction calculations (n1_frac
,n_frac
) vectoriallyP_left
,P_right
) for all states simultaneouslyPerformance Impact by Test Case Size:
The vectorized approach transforms O(N) scalar operations into O(1) vector operations, with the performance gain scaling significantly with problem size. For large N values typical in Markov chain applications, this provides substantial computational savings.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-KMR_Markov_matrix_sequential-mggwpynf
and push.