Skip to content

Instantly share code, notes, and snippets.

@thuwarakeshm
Last active August 13, 2023 17:57
Show Gist options
  • Save thuwarakeshm/efff17c405485f5fd24e9c12bcd3e73e to your computer and use it in GitHub Desktop.
Save thuwarakeshm/efff17c405485f5fd24e9c12bcd3e73e to your computer and use it in GitHub Desktop.
faster_arrays
import numpy as np
import timeit
def matrix_muliplication_with_np(matrix1, matrix2):
return np.matmul(matrix1, matrix2)
def matrix_multiplication_with_for_loop(matrix1, matrix2):
result = np.zeros((len(matrix1), len(matrix2[0])))
for i in range(len(matrix1)):
for k in range(len(matrix2)):
for j in range(len(matrix2[0])):
result[i][j] += matrix1[i][k] * matrix2[k][j]
return result
if __name__ == "__main__":
matrix1 = np.random.randint(1, 10, (1000, 1000))
matrix2 = np.random.randint(1, 10, (1000, 1000))
print(
"Matrix multiplication with numpy: ",
timeit.timeit(lambda: matrix_muliplication_with_np(matrix1, matrix2), number=1),
)
print(
"Matrix multiplication with for loop: ",
timeit.timeit(
lambda: matrix_multiplication_with_for_loop(matrix1, matrix2), number=1
),
)
import numpy as np
import timeit
def sum_with_for_loop(array) -> int:
sum = 0
for i in array:
sum += i
return sum
def sum_with_np_sum(array) -> int:
return np.sum(array)
if __name__ == "__main__":
array = np.random.randint(0, 100, 1000000)
# print time for for loop
print(timeit.timeit(lambda: sum_with_for_loop(array), number=100))
# print time for np.sum
print(timeit.timeit(lambda: sum_with_np_sum(array), number=100))
import numpy as np
import timeit
def sum_product_with_for_loop(array1, array2) -> int:
sum = 0
for i, j in zip(array1, array2):
sum += i * j
return sum
def sum_product_with_np_sum(array1, array2) -> int:
return np.sum(array1 * array2)
if __name__ == "__main__":
array1 = np.random.randint(0, 100, 1000000)
array2 = np.random.randint(0, 100, 1000000)
# Print the time taken to execute the function
print(timeit.timeit(lambda: sum_product_with_for_loop(array1, array2), number=100))
print(timeit.timeit(lambda: sum_product_with_np_sum(array1, array2), number=100))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment