⚡️ Speed up function draw
by 390%
#8
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.
📄 390% (3.90x) speedup for
draw
inquantecon/random/utilities.py
⏱️ Runtime :
2.72 milliseconds
→556 microseconds
(best of241
runs)📝 Explanation and details
The key optimization replaces a Python loop with vectorized NumPy operations in the
draw
function's multiple sample case.What changed:
for i in range(size): out[i] = searchsorted(cdf, rs[i])
with a single vectorized call:out = np.searchsorted(cdf, rs, side='right')
np.empty
allocation sincenp.searchsorted
returns the output array directlyWhy this is faster:
The original code performs
size
individual calls to the customsearchsorted
function in Python, each requiring loop overhead and function call overhead. The optimized version leverages NumPy's highly optimized C implementation that processes the entire array in one operation, eliminating Python loop overhead entirely.Performance characteristics:
size=0
show slight regression due to NumPy's overhead for empty arrays, but these are uncommon scenariosThe optimization is most effective when
size
is an integer (vectorizable case), while preserving the original behavior for single draws and non-integer sizes.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-draw-mgg0qwcu
and push.