矩阵乘法返回错误的矩阵python并行

时间:2019-03-01 15:57:52

标签: python matrix multiprocessing multiplication

我有一个学校项目,在这里我必须做一些python并行功能。其中之一是矩阵乘法(我不能使用numpy)。我尝试在多线程中执行此操作,但是它太慢了,建议在多处理中执行。它快得多,但是有一个问题。仅当使用一个过程时,我才能获得正确的矩阵。有人可以帮忙吗?这是代码:

import numpy as np
import time
import multiprocessing.dummy as mp

min = -10
max = 10
n = 10
x = ((np.random.rand(n, n) * (max - min) ) + min).astype('int')
y = ((np.random.rand(n, n) * (max - min) ) + min).astype('int')

z = [[0 for i in range(n)] for j in range(n)]
jump = 0

def matrixMult(start):
    for i in range(start, start + jump):
        print("HEJ")
        for k in range(n):
            for j in range(n):
                z[i][j] += x[i][k] * y[k][j]

def multPrepare(x, y, i):
    pool = mp.Pool(i)
    pool.map(matrixMult, range(0, n, jump))
    return z

if __name__ == '__main__':

    i = 1
    while i < 5:
        start_time = time.time()
        jump = int(round(n / i))
        z = multPrepare(x, y, i)
        print("number of cores: " + str(i) + ", TIME: "+ str(time.time()-start_time) + " seconds")
        i += 1

    print(z)
    print(z == x.dot(y))

只有当i = 1时,结果矩阵才是正确的。

0 个答案:

没有答案