Comment by credit_guy
2 months ago
"Here’s how you can create a test case to compare the performance of the for-loop method and the vectorized method using numpy.linalg.solve. I will provide the Python code for you to test this."
import numpy as np
import time
# Create random test data
np.random.seed(42) # For reproducibility
A = np.random.rand(100, 5, 5) # 100 random 5x5 matrices
x = np.random.rand(100, 5) # 100 random vectors of length 5
# Method 1: For-loop approach
start_time = time.time()
y_loop = np.empty_like(x)
for i in range(100):
y_loop[i, :] = np.linalg.solve(A[i, :, :], x[i, :])
loop_time = time.time() - start_time
# Method 2: Vectorized approach
start_time = time.time()
y_vectorized = np.linalg.solve(A, x)
vectorized_time = time.time() - start_time
# Verify correctness
correctness = np.allclose(y_loop, y_vectorized)
# Print results
print(f"For-loop method time: {loop_time:.6f} seconds")
print(f"Vectorized method time: {vectorized_time:.6f} seconds")
print(f"Results are {'correct' if correctness else 'incorrect'}")
For-loop method time: 0.001004 seconds Vectorized method time: 0.000000 seconds Results are correct
No comments yet
Contribute on Hacker News ↗