Python implements a simple parallel matrix multiplication

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.