The matrix multiplication method used in this paper is to multiply the rows of a matrix and the columns of two matrices without affecting each other. Suppose a (M,n) represents the M-row, N-column of the Matrix. So C (m,m) =a (m,n)
B (n,m):
Calculate C matrix when decomposed into:
Process-1:
C (A) = A (1,:)B (:, 1)
Process-2:
C (from) = A (1,:) * B (:, 2)
..........
Process-m
C (m,m) = A (M,:) * B (:, M)
Realize the source code:
Import multiprocessing #导入多进程模块 for multi-process
Import OS #验证, the ID of the print process
Import NumPy as NP #这个模块是为了实现矩阵乘法
def matrix_muti (i,j):
Print (' current process is {0} '. Format (Os.getpid ())) #打印执行该函数时候的进程
A = [[1, 2], [5, 8]]
B = [[4, 8], [6, 5]]
A = Np.array (a)
b = Np.array (b)
#print (I,J)
Try
Print (sum (a[i,:]*b[:,j]))
Except
Pass
If name = = 'main':
M=1
N=0
Print (' parent process is {0} '. Format (Os.getpid ())) #获取父进程id
For I in range (4):
#控制矩阵的行列数字变化
N=n+1
If n% 3 = = 0:
m = m + 1
n = 1
#查看下标变化是否正确 print(‘下标变化:‘,m-1,n-1) p = multiprocessing.Process(target=matrix_muti,args=(m-1,n-1,)) #固定格式,使用4个子进程求矩阵的乘积 p.start() #开始p.join()
Copy time to run under, found that the code is copied to pycharm the indentation changes, need to manually adjust, or will error
贴出运行结果如下:
Python implements a simple parallel matrix multiplication