python multiprocessing parallel

分别通过serial和MPI,数值计算pi, 比较计算速率。

python multiprocessing parallel_第1张图片

import sys
import time
import multiprocessing as mp
import numpy as np


numint=int(sys.argv[1])
def integral_pi(numint):
    integral=0.0
    x=np.zeros(numint,float)
    dx=1.0/numint
    for i in range(0,numint):
        x[i]=i/numint
        integral+=np.sqrt(1-x[i]**2)*dx
    return integral


num_thread=int(sys.argv[2])
def fx(x):
    dx=1.0/numint
    funcx=np.sqrt(1-x**2)*dx
    return funcx

def integral1_pi(numint):
    integral=0.0
    x=np.zeros(numint,float)
    for i in range(0,numint):
        x[i]=i/numint
    pool=mp.Pool(num_thread)
    integral=sum(pool.map(fx,x))
    pool.close()
    return integral

if __name__=='__main__':

    time3=time.time()
    intpi=4*integral1_pi(numint)
    print('the caculated pi value is ',intpi)
    time4=time.time()
    print('the time elapse(mp) is ',time4-time3)


    time1=time.time()
    intpi=4*integral_pi(numint)
    print('the caculated pi value is ',intpi)
    time2=time.time()
    print('the time elapse is ',time2-time1)

为了比较, integral_pi 是Serial calculation,integral1_pi是Multiprocessing calculation。

在Ubuntu Terminal中运行程序: python3 hello.py 100000 10

MP竟然比serial计算慢。待求证。这里结果和预期不同。

你可能感兴趣的:(Parallel,Computing)