1. Michael Lee
  2. cs450

Commits

Michael Lee  committed 8aefba8

Adding matrix multiplication example in Python

  • Participants
  • Parent commits a47293e
  • Branches master

Comments (0)

Files changed (1)

File concur/python/matrix_mul.py

View file
+import random
+import sys
+from time import time
+from pprint import pprint
+from multiprocessing import Pool
+from timeit import Timer
+import os
+
+def seq_mat_mult():
+    result = [[0 for col in range(len(B[0]))]
+              for row in range(len(A))]
+    for i in range(len(result)):
+        result_row = result[i] # simple optimization
+        for j in range(len(result[0])):
+            for k in range(len(A[0])):
+                result_row[j] += A[i][k] * B[k][j]
+    return result
+
+def mat_mult_row(r):
+    result = [0 for col in range(len(B[0]))]
+    for j in range(len(result)):
+        for k in range(len(A[0])):
+            result[j] += A[r][k] * B[k][j]
+    return result
+
+def sum_mat(m):
+    return sum(map(sum, m))
+
+A = []
+B = []
+if __name__ == '__main__':
+    n_rows =  n_cols = int(sys.argv[1]) # square matrixes only!
+    n_procs = int(sys.argv[2])
+
+    random.seed(0)
+    A = [[random.randint(1, 9) for _ in range(n_cols)] for _ in range(n_rows)]
+    B = [[random.randint(1, 9) for _ in range(n_cols)] for _ in range(n_rows)]
+
+    for i in range(5):
+        print('Pass {}'.format(i))
+
+        start = time()
+        C = seq_mat_mult()
+        end = time()
+        print('(SEQ) Result sum: {}'.format(sum_mat(C)))
+        print('(SEQ) Elapsed: {:0.1f} ms'.format(1000*(end-start)))
+        
+        pool = Pool(processes=n_procs)
+        start = time()
+        C = pool.map(mat_mult_row, range(n_rows))
+        end = time()
+        print('(MAP) Result sum: {}'.format(sum_mat(C)))
+        print('(MAP) Elapsed: {:0.1f} ms'.format(1000*(end-start)))
+        print()