⚡️ Speed up function matrix_inverse by 534%
#21
Closed
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.
📄 534% (5.34x) speedup for
matrix_inverseinsrc/numpy_pandas/matrix_operations.py⏱️ Runtime :
84.2 milliseconds→13.3 milliseconds(best of187runs)📝 Explanation and details
Here's an optimized version of your
matrix_inversefunction, focusing on avoiding Python for-loops in favor of fast NumPy array operations. The heart of your performance problem is the double for-loop, which can be partly vectorized.We also avoid repeated slicing and use in-place operations for better cache efficiency.
Key optimizations:
/=instead of creating new arrays for each row scaling.j > iandj < irows are updated in a block.astype(float, copy=False)so the input is avoided being copied if already float.This will drastically reduce the time spent on row subtraction, which was previously the slowest part.
If you want even more performance, consider using
np.linalg.invfor production unless you need to teach the algorithm!Let me know if you want a pure Cython/Numba optimized version for even more speed.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-matrix_inverse-mc5i7sy2and push.