forked from modular/mojo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpymatmul.py
60 lines (46 loc) · 1.87 KB
/
pymatmul.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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2023, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Simple program demonstrating a naive matrix multiplication in Python
import importlib
import sys
import subprocess
if not importlib.find_loader("numpy"):
print("Numpy not found, installing...")
subprocess.check_call([sys.executable, "-m", "pip", "install", "numpy"])
import numpy as np
from timeit import timeit
class PyMatrix:
def __init__(self, value, rows, cols):
self.value = value
self.rows = rows
self.cols = cols
def __getitem__(self, idxs):
return self.value[idxs[0]][idxs[1]]
def __setitem__(self, idxs, value):
self.value[idxs[0]][idxs[1]] = value
def matmul_python(C, A, B):
for m in range(C.rows):
for k in range(A.cols):
for n in range(C.cols):
C[m, n] += A[m, k] * B[k, n]
def benchmark_matmul_python(M, N, K):
A = PyMatrix(list(np.random.rand(M, K)), M, K)
B = PyMatrix(list(np.random.rand(K, N)), K, N)
C = PyMatrix(list(np.zeros((M, N))), M, N)
secs = timeit(lambda: matmul_python(C, A, B), number=2) / 2
gflops = ((2 * M * N * K) / secs) / 1e9
print(gflops, "GFLOP/s")
return gflops
if __name__ == "__main__":
print("Throughput of a 128x128 matrix multiplication in Python:")
benchmark_matmul_python(128, 128, 128)