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

##### 问题描述投票：0回答：1

``````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)
``````

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

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

``````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 -n 4 python script_name.py
``````