我是使用 Python 的 MPI 新手,在这里遇到了一些问题。这是我的代码:
from mpi4py import MPI
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
if rank == 0:
a = 1
comm.bcast(a, root=0)
s = comm.reduce(a, op=MPI.SUM)
print 'From process 0, sum =', s
elif rank == 1:
b = 2
comm.bcast(b, root=1)
x = comm.reduce(b, op=MPI.SUM)
print 'From process 1, sum =', x
Run Code Online (Sandbox Code Playgroud)
我想打印:From process PROCESS_NUMBER, sum = 3
进程 0 打印正确,但进程 1 打印 None。
我不明白为什么。有人可以帮助我吗?
小智 4
Bcast, Reduce)都应该在所有进程上调用,因此将其放在if rank == N
语句中是不正确的。root=1.a = comm.bcast(a, root=0)更正的代码:
from mpi4py import MPI
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
if rank == 0:
a = 1
else:
a = None
a = comm.bcast(a, root=0)
s = comm.reduce(a, op=MPI.SUM)
if rank == 0:
print 'From process 0, sum =', s
if rank == 1:
b = 2
else:
b = None
b = comm.bcast(b, root=1)
x = comm.reduce(b, op=MPI.SUM, root=1)
if rank == 1:
print 'From process 1, sum =', x
Run Code Online (Sandbox Code Playgroud)
在3个进程上运行的结果:
From process 0, sum = 3
From process 1, sum = 6
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
334 次 |
| 最近记录: |