⚡️ Speed up function draw by 616%
#57
Open
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.
📄 616% (6.16x) speedup for
drawinquantecon/random/utilities.py⏱️ Runtime :
1.36 milliseconds→190 microseconds(best of250runs)📝 Explanation and details
The optimized code achieves a 6.15x speedup by replacing the pure Python loop-based search with Numba JIT-compiled binary search functions.
Key Optimizations:
JIT Compilation with Numba: Added
@njit(cache=True)decorators to create compiled binary search functions (_searchsorted_jitand_draw_jit) that execute at near-C speeds instead of interpreted Python.Custom Binary Search: Replaced the original
searchsortedfunction calls with a custom binary search implementation that's optimized for Numba compilation, reducing algorithmic complexity from O(n) linear search to O(log n) binary search.Vectorized Processing: The
_draw_jitfunction processes all random samples in a single compiled function call, eliminating the Python loop overhead from the original implementation.Performance Impact:
np.asarray()conversion costsHot Path Benefits:
Based on the function references showing
draw_jittedusage in test files, this function appears to be used in Monte Carlo simulations and random sampling workflows where it would be called repeatedly. The JIT compilation cost is amortized over multiple calls, and the O(log n) vs O(n) algorithmic improvement becomes significant for larger probability distributions.The optimization is most effective for workloads involving repeated sampling from moderate-to-large CDFs, which are common in quantitative economics applications.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-draw-mja23ef6and push.