python mpi简单应用
程序员文章站
2022-03-06 13:56:33
...
借鉴博客学习一下py下mpi的基本语法
https://blog.csdn.net/u012526003/article/details/80299113
发送
comm.send( data, pid)
接受
data_recv = comm.recv(data)
广播:
comm.bcast(data, 0) (None, 0 )
散播:均分
comm_scatter(data, root)
收集数据:
comm_gather(data, pid)
规约:
comm_reduce(data , pid , op=MPI.SUM)
下面让我们来写一个最简单的入门程序——求π值
没找到mpi的函数库,原来c的mpi里面的wtime函数在Python中没有,以此注意n的传值,并且保证主进程最后一个结束输出pi
from mpi4py import MPI
def func(x):
return (4.0 / (1.0 + x * x))
comm = MPI.COMM_WORLD
comm_rank = comm.Get_rank()
comm_size = comm.Get_size()
PI = 3.141592653589
if comm_rank == 0:
n = 10000
# starttime = MPI.wtime()
n = comm.bcast(n if comm_rank == 0 else None, root=0)
print("n = %d" % n)
h = 1.0/n
sum = 0.0
for i in range(comm_rank, n, comm_size):
x = h * (0.5 + i)
sum += func(x)
npi = h * sum
mypi = comm.reduce(npi, root=0, op=MPI.SUM)
if comm_rank == 0:
#endtime = MPI.wtime()i
#waiting other end
for i in range(1,comm_rank):
x = comm.recv(n, i)
print("pi is %.16f"% mypi)
else:
comm.send(n, 0)
# print("err = %f\n time is %f"% (mypi-PI), (endtime-starttime))
下面让我们来测试一下程序
上一篇: webpack的基础使用
下一篇: DelphiXE矩阵乘法的并行设计