⚡️ Speed up method IVP._integrate_fixed_trajectory
by 16%
#11
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
IVP._integrate_fixed_trajectory
inquantecon/_ivp.py
⏱️ Runtime :
14.9 milliseconds
→12.8 milliseconds
(best of311
runs)📝 Explanation and details
The optimization replaces the O(n²) performance bottleneck caused by repeated
np.vstack()
operations with an efficient pre-allocation strategy.Key optimization:
np.vstack()
to grow the array (which requires copying all existing data each time), the code pre-allocates chunks of 128 rows and grows by additional chunks only when needed.np.hstack()
andnp.vstack()
calls with direct array assignment using indexing (sol[idx, 0] = self.t
).Why it's faster:
The original code's
np.vstack()
operations had O(n) cost per iteration, leading to O(n²) total complexity as the solution array grew. The line profiler shows 8.5% of runtime was spent on vstack operations. The optimized version achieves amortized O(1) growth by pre-allocating space and only occasionally resizing, reducing memory allocations and data copying.Performance gains by test type:
The optimization maintains identical output format and behavior while dramatically improving scalability for longer integration trajectories.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-IVP._integrate_fixed_trajectory-mggp3cyz
and push.