⚡️ Speed up function compute_fixed_point by 48%
#52
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.
📄 48% (0.48x) speedup for
compute_fixed_pointinquantecon/_compute_fp.py⏱️ Runtime :
2.45 milliseconds→1.66 milliseconds(best of250runs)📝 Explanation and details
The optimized code achieves a 48% speedup by replacing NumPy's
np.max(np.abs(new_v - v))with Numba-compiled functions that compute maximum absolute differences more efficiently.Key optimizations:
Numba-compiled difference calculation: Added
@njit(cache=True, fastmath=True)decorated functions_max_abs_diff()and_max_abs_diff_scalar()that replace the NumPy operation with optimized compiled loops. These functions avoid NumPy's intermediate array allocation and use direct iteration over flattened arrays.Smart dispatch logic: The code detects numpy arrays with numeric dtypes (
v.dtype.kind in 'fc') at the start of the iteration loop and uses the appropriate Numba function throughout the loop, avoiding repeated type checking.Specialized scalar handling: For scalar floating-point values, uses
_max_abs_diff_scalar()which simply computesabs(new_v - v)without NumPy overhead.Enhanced
_is_approx_fp()function: Applied the same Numba optimization to the approximate fixed-point checking function used in the imitation game method.Why this provides speedup:
np.abs(new_v - v)creates intermediate arrays, while Numba computes differences in-placePerformance benefits by test case:
The optimization shows significant gains across different scenarios:
test_simple_contraction_scalar)_is_approx_fpHot path impact:
Based on function references showing
compute_fixed_pointis called in tight loops within quantecon's test suite for convergence analysis, this optimization significantly improves performance for iterative economic modeling workloads where fixed-point computation is repeatedly called.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-compute_fixed_point-mj9zwgkwand push.