Python list VS Numpy for matrix multiply

Hello!! I’m Coconut~

This time, running simple test for matrix multiply with python list and python numpy

Run environment : 800 by 400 X 400 by 800 => 800 by 800

Case1: python list for loop matmul

Case2: numpy ndarray matmul

In this test, Numpy calculation is 180 times faster than python list loop calculation

If you want view this test code, move to below

# -*- coding: utf-8 -*-
import numpy as np
from datetime import datetime

# 일반적인 행렬
normal_matrix1 = [[x for x in range(1, 401)] for e in range(1, 801)]
# numpy 행렬 선언
np_mat1 = np.array(normal_matrix1)

# 행렬2
normal_matrix2 = [[x for x in range(401, 1201)] for e in range(1, 401)]
# numpy 행렬2 선언
np_mat2 = np.array(normal_matrix2)


print("1 : " + str(np_mat1) + str(np_mat1.shape))
print("2 : " + str(np_mat2) + str(np_mat2.shape))
start = datetime.now()
# print(np_test + np2_test)
print("-----------------------------------------------------------------")
mul = np.matmul(np_mat1, np_mat2)
print(str(mul) + " / dimension : " + str(mul.shape))
print("-----------------------------------------------------------------")
end = datetime.now()

# numpy 벡터연산 걸린 시간
print("numpy duration_time : " + str(end - start))
print("-----------------------------------------------------------------")

result = [[0 for x in range(1, 801)] for e in range(1, 801)]

start_normal = datetime.now()
for i in range(len(normal_matrix1)):
for j in range(len(normal_matrix2[0])):
for k in range(len(normal_matrix2)):
result[i][j] += normal_matrix1[i][k] * normal_matrix2[k][j]

end_normal = datetime.now()

# list 연산 걸린 시간
print(str(result))
print("-----------------------------------------------------------------")
print("normal calculation duration_time : " + str(end_normal - start_normal))
print("-----------------------------------------------------------------")

The post Python list VS Numpy for matrix multiply appeared first on Coconut.

0 Comments