780_APM
780_APM

Reputation: 43

How can I make Matrix Multiplication Code run in parallel?

I have a block of code that takes user input and creates them into matrices but i need them to run in parallel as appose to running the code as one single process. I have no clue how to do so, i started reading into NumPy but haven't really grasped it.

import timeit
start = timeit.default_timer()

def getMatrix(name):
    matrixCreated = []
    i = 0
    while True:
        i += 1
        row = input('\nEnter elements in row %s of Matrix %s (separated by commas)\nOr -1 to exit: ' % (i, name))
        if row == '-1':
            break
        else:
            strList = row.split(',')
            matrixCreated.append(list(map(int, strList)))
return matrixCreated


def getColAsList(matrixToManipulate, col):
    myList = []
    numOfRows = len(matrixToManipulate)
    for i in range(numOfRows):
        myList.append(matrixToManipulate[i][col])
    return myList


def getCell(matrixA, matrixB, r, c):
    matrixBCol = getColAsList(matrixB, c)
    lenOfList = len(matrixBCol)
    productList = [matrixA[r][i] * matrixBCol[i] for i in range(lenOfList)]
    return sum(productList)


matrixA = getMatrix('A')
matrixB = getMatrix('B')

rowA = len(matrixA)
colA = len(matrixA[0])
rowB = len(matrixB)
colB = len(matrixB[0])

result = [[0 for p in range(colB)] for q in range(rowA)]

if (colA != rowB):
    print('The two matrices cannot be multiplied')
else:
    print('\nThe result is')
    for i in range(rowA):
        for j in range(colB):
            result[i][j] = getCell(matrixA, matrixB, i, j)
        print(result[i])

stop = timeit.default_timer()
print('Time: ', stop - start)

I also have a timer on the code to pint the time taken, but as its a programme that takes user input it is directly related to how long it takes to process in real-time, is there a way i can time it just to execute? I need to compare how making this code run in parallel can decrease run-time.

Upvotes: 1

Views: 380

Answers (2)

Uri Goren
Uri Goren

Reputation: 13672

numpy is an efficient C implementation, while jax is a an efficient parallel implementation that supports also GPU/TPU.

Both of then would run faster than your current python implementation.

Import numpy or jax

import numpy as np

or

import jax.numpy as np

Then create the matrices

A = np.array(getMatrix('A'))
B = np.array(getMatrix('B'))

And output the matrix multiplication

C = A @ B
print (C)

Upvotes: 4

Károly Szabó
Károly Szabó

Reputation: 1273

If you want only the time of execution of the matrix multiplication than move the start after the user input, like this:

...
matrixA = getMatrix('A')
matrixB = getMatrix('B')

start = timeit.default_timer()    

rowA = len(matrixA)
colA = len(matrixA[0])
rowB = len(matrixB)
colB = len(matrixB[0])

...

stop = timeit.default_timer()
print('Time: ', stop - start)

Upvotes: 1

Related Questions