Multiprocessing nested python loops

a 夏天 提交于 2021-01-05 12:43:58

问题


To improve my code which has one heavy loop I need a speed up. How can I implement multiprocessing for a code like this? (a is typical of size 2 and l up to 10)

for x1 in range(a**l):
    for x2 in range(a**l):
        for x3 in range(a**l):
            output[x1,x2,x3] = HeavyComputationThatIsThreadSafe1(x1,x2,x3)

回答1:


If the HeavyComputationThatIsThreadSafe1 function only uses arrays and not python objects, I would using a concurrent futures (or the python2 backport) ThreadPoolExecutor along with Numba (or cython) with the GIL released. Otherwise use a ProcessPoolExecutor.

See:

http://numba.pydata.org/numba-doc/latest/user/examples.html#multi-threading

You'd want to parallelize the calculation at the level of the outermost loop and and then fill output from the chunks resulting from each thread/process. This assumes the cost of doing so is much cheaper than the computation, which should be the case.



来源:https://stackoverflow.com/questions/37092648/multiprocessing-nested-python-loops

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!