lit*_*itd 25 python multiprocessing
我想总结如下值:
from multiprocessing import Pool
from time import time
N = 10
K = 50
w = 0
def CostlyFunction(z):
r = 0
for k in xrange(1, K+2):
r += z ** (1 / k**1.5)
print r
w += r
return r
currtime = time()
po = Pool()
for i in xrange(N):
po.apply_async(CostlyFunction,(i,))
po.close()
po.join()
print w
print '2: parallel: time elapsed:', time() - currtime
Run Code Online (Sandbox Code Playgroud)
我无法得到所有r值的总和.
Jus*_*eel 19
如果你打算像那样使用apply_async,那么你必须使用某种共享内存.此外,您需要放置启动多处理的部分,以便仅在初始脚本调用时完成,而不是通过池化进程调用.这是用map做的一种方法.
from multiprocessing import Pool
from time import time
K = 50
def CostlyFunction((z,)):
r = 0
for k in xrange(1, K+2):
r += z ** (1 / k**1.5)
return r
if __name__ == "__main__":
currtime = time()
N = 10
po = Pool()
res = po.map_async(CostlyFunction,((i,) for i in xrange(N)))
w = sum(res.get())
print w
print '2: parallel: time elapsed:', time() - currtime
Run Code Online (Sandbox Code Playgroud)
这是我在python示例文档中找到的最简单的示例:
from multiprocessing import Pool
def f(x):
return x*x
if __name__ == '__main__':
pool = Pool(processes=4) # start 4 worker processes
result = pool.apply_async(f, [10]) # evaluate "f(10)" asynchronously
print result.get(timeout=1) # prints "100" unless your computer is *very* slow
print pool.map(f, range(10)) # prints "[0, 1, 4,..., 81]"
Run Code Online (Sandbox Code Playgroud)
即使我能理解它也很简单.
注意result.get()是触发计算的原因.