forked from tinyendian/swcmeethpc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
matmulti1.py
36 lines (29 loc) · 1.06 KB
/
matmulti1.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import numpy as np
import timeit
def matmul(X,Y):
# initialise result matrix Z
Z = np.zeros_like(X)
# iterate through rows of matrix X
for i in range(X.shape[0]):
# iterate through columns of matrix Y
for j in range(Y.shape[1]):
# iterate through rows of Y
for k in range(Y.shape[0]):
Z[i,j] += X[i,k] * Y[k,j]
# wrapper to make test function callable for timing
def wrapper(func, *args, **kwargs):
def wrapped():
return func(*args, **kwargs)
return wrapped
# set number of rows and columns
N = 100
# generate square matrices and fill with random numbers
X = np.random.rand(N,N)
Y = np.random.rand(N,N)
# set the number of times the multiplication will be repeated
Ntimes = 10
# run matrix multiplication "Ntimes" times and get runtime minimum
best_runtime = min(timeit.repeat(wrapper(matmul,X,Y), number = 1, repeat = Ntimes))
# output
print "Running nested for loops {0} times...".format(Ntimes)
print "Best runtime [seconds]: {0:.4}".format(best_runtime)