⚡️ Speed up method IVP._integrate_variable_trajectory by 687%
#60
+18
−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.
📄 687% (6.87x) speedup for
IVP._integrate_variable_trajectoryinquantecon/_ivp.py⏱️ Runtime :
2.00 seconds→255 milliseconds(best of5runs)📝 Explanation and details
The optimization replaces the inefficient dynamic array growth pattern with a pre-allocated buffer and doubling strategy, delivering a 686% speedup.
Key Optimizations:
Pre-allocated Buffer: Instead of starting with a single row and using
np.vstack()for each step, the code pre-allocates a buffer of 1024 rows usingnp.empty(). This eliminates the O(n²) memory allocation overhead from repeated array concatenation.Exponential Growth Strategy: When the buffer fills up, it doubles in size rather than growing by one row. This ensures amortized O(1) insertion cost per step instead of O(n) cost for each
np.vstack()operation.Direct Array Assignment: Values are written directly to pre-allocated positions (
solution[row, 0] = self.t) rather than creating intermediate arrays withnp.hstack()and concatenating them.Performance Impact Analysis:
The line profiler shows the dramatic improvement - the original code spent 78.1% of time in
np.vstack()operations (40 billion nanoseconds), while the optimized version eliminates this bottleneck entirely. The optimized version shows most time is now spent on the actual ODE integration (self.integrate()at 65.4%), which is the unavoidable computational work.Test Case Performance:
test_large_scale_multivarshows 891% speedup)The optimization is most effective for workloads with longer integration trajectories, making it particularly valuable for numerical simulations requiring many integration steps.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-IVP._integrate_variable_trajectory-mja6uoreand push.