⚡️ Speed up function numerical_integration_rectangle
by 56%
#17
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.
📄 56% (0.56x) speedup for
numerical_integration_rectangle
insrc/numpy_pandas/numerical_methods.py
⏱️ Runtime :
1.53 milliseconds
→982 microseconds
(best of237
runs)📝 Explanation and details
Here are the main bottlenecks per your profiling.
result += f(x)
is very slow: calling a Python function is expensive in tight loopsx = a + i * h
is nextfor i in range(n)
) adds overheadOptimization strategies:
f
function can work on arrays, but we can provide a fast path and fall back otherwise.functools.lru_cache
to cache repeated calls iff
is expensive and pure, but often this helps only for certain functions.a + i*h
can be replaced with a precomputed numpy array ofx
values.Here's a rewritten version that will be much faster for
f
functions that accept numpy arrays, but will still work with all standard Python callables (falling back to the original loop).Explanation:
f
is numpy-aware (works with numpy arrays), the whole integration will run in compiled code (very fast).a + i * h
is already cheap.Note:
If you are not allowed to use numpy (or want to further speed up for "slow" pure-Python functions), consider using Cython or numba. But for pure Python, numpy vectorization gives you the biggest, simplest speedup.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-numerical_integration_rectangle-mc5fsdpy
and push.