对Python多进程池进行性能分析
我想在一个多进程的池子里,使用cProfile.runctx()来查看我的代码在多进程运行时的瓶颈在哪里。下面是我想做的一个简单例子:
from multiprocessing import Pool
import cProfile
def square(i):
return i*i
def square_wrapper(i):
cProfile.runctx("result = square(i)",
globals(), locals(), "file_"+str(i))
# NameError happens here - 'result' is not defined.
return result
if __name__ == "__main__":
pool = Pool(8)
results = pool.map_async(square_wrapper, range(15)).get(99999)
print results
可惜的是,当我在性能分析器里执行“result = square(i)”时,'result'这个变量在它被调用的地方并没有变化。我该怎么做才能实现我想要的效果呢?
1 个回答
8
试试这个:
def square_wrapper(i):
result = [None]
cProfile.runctx("result[0] = square(i)", globals(), locals(), "file_%d" % i)
return result[0]