⚡️ Speed up method LinearStateSpace.impulse_response by 175%
#58
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.
📄 175% (1.75x) speedup for
LinearStateSpace.impulse_responseinquantecon/_lss.py⏱️ Runtime :
1.62 milliseconds→590 microseconds(best of250runs)📝 Explanation and details
The optimization achieves a 174% speedup by leveraging Numba's Just-In-Time (JIT) compilation to accelerate matrix operations in the core computational loop of
impulse_response.Key optimizations applied:
Numba JIT compilation: The main computational logic is extracted into a separate
_impulse_response_numbamethod decorated with@njit(cache=True). This compiles the matrix multiplication-heavy loop to optimized machine code, dramatically improving performance of the repeated@operations.Efficient memory operations: The numba implementation uses explicit
.copy()calls and optimized matrix multiplication patterns that JIT can better optimize compared to Python's interpreted execution.Input validation preservation: The optimized version maintains identical error behavior by validating the
jparameter withrange(j)before delegating to the numba function, ensuring TypeError is raised for invalid types like floats, strings, or None.Performance characteristics:
The optimization is particularly effective for the common use cases in linear state space models where impulse response calculations are performed repeatedly with varying matrix sizes and iteration counts. The cached JIT compilation ensures subsequent calls avoid compilation overhead, making this ideal for hot path usage in econometric modeling workflows.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-LinearStateSpace.impulse_response-mja2kt97and push.