如何实现在使用Python MPI不同的内核简单的并行计算

问题描述 投票:0回答:1

我想实现并联一个简单的计算任务。比方说,我有两个阵列包括每2个分量,我想通过一个总结这些阵列之一的组件,并将它们存储在一个新的数组。有组分(2×2)的4种组合。一个简单的代码可以写在使用仅1核心串行和求和操作实现对核心4倍。下面是代码:

a = [1 , 5]
b = [10 , 20]

d = []

for i in range(2):
    for j in range(2):

        c = a[i] + b[j]
        d.append(c)

print (d)

现在我想用MPI并行运行上面的代码使用4个不同的内核在我的电脑,使其更快。有了这样说我希望被在所分配的芯实现的每个组合(例如4上4个不同的核求和操作)。这里是我可以导入MPI:

from mpi4py import MPI
mpi_comm = MPI.COMM_WORLD
rank_process = mpi_comm.rank

我从来没有使用并行计算,所以它看起来有点混乱给我。我想知道,如果有人可以帮助我。在此先感谢您的时间。

python-3.x parallel-processing mpi
1个回答
1
投票

您可以使用Create_cart到MPI进程分配到矩阵的部分,这样他们可以给指数ij在您的序列例子。这是解决方案,

from mpi4py import MPI
mpi_comm = MPI.COMM_WORLD
rank = mpi_comm.rank
root = 0

#Define data
a = [1 , 5]
b = [10 , 20]
d = []

#Print serial solution
if rank == 0:
    for i in range(2):
        for j in range(2):
            c = a[i] + b[j]
            d.append(c) 

    print("Serial soln = ", d)

#Split domain into 2 by 2 comm and run an element on each process
cart_comm = mpi_comm.Create_cart([2, 2])
i, j = cart_comm.Get_coords(rank)
d = a[i] + b[j]

#Print solns on each process, note this will be jumbled
# as all print as soon as they get here
print("Parallel soln = ", d)

# Better to gather and print on root
ds = mpi_comm.gather(d, root=root)
if rank == root:
    print("Parallel soln gathered = ", ds)

在那里你喜欢的东西,

('Serial soln = ', [11, 21, 15, 25])
('Parallel ('Parallel soln = '('Parallel soln = 'soln = ', 11)
, 21)
('Parallel soln = ', 15)
, 25)
('Parallel soln gathered = ', [11, 21, 15, 25])

其中平行输出混乱。注意你需要如下与mpiexec运行,

mpiexec -n 4 python script_name.py

其中script_name.py是你的脚本名称。

我不知道这是你如何使用MPI一个很好的例子。值得一对MPI一般阅读起来看看一些规范的例子。特别要注意的是,因为每个过程是独立的,它自己的数据,你应该对问题的工作,你最多可以将它分成部分。在你的榜样,所有列表的ab的每个进程单独定义每个过程只使用其中的一小部分。每个过程之间的唯一区别是从create_cart,其确定它们使用的“全局”阵列的哪一部分的秩(0〜3)和以后的二维笛卡尔indixes。

更好的解决方案,更贴近你怎么会在实践中使用,这可能是撒大矩阵的部分许多过程,利用矩阵的一部分做了一些工作,并收集回来的解决方案,以获得完整矩阵(再次,见其中包括这样的事情的例子)。

© www.soinside.com 2019 - 2024. All rights reserved.