This program compares the time to add arrays using broadcasting versus a manual loop. Broadcasting is much faster and simpler.
import numpy as np
import time
# Create a large 2D array
large_array = np.ones((1000, 1000))
# Create a smaller 1D array
small_array = np.arange(1000)
# Time adding with broadcasting
start = time.time()
result_broadcast = large_array + small_array
end = time.time()
print(f"Broadcasting time: {end - start:.6f} seconds")
# Time adding with explicit loop (slow way)
start = time.time()
result_loop = np.empty_like(large_array)
for i in range(1000):
result_loop[i, :] = large_array[i, :] + small_array
end = time.time()
print(f"Loop time: {end - start:.6f} seconds")
# Check if results are the same
print("Results are equal:", np.array_equal(result_broadcast, result_loop))