繁体   English   中英

Python 中的多处理嵌套循环?

[英]Multi-Processing nested loops in Python?

我有一个多嵌套的 for 循环,我想在 Python 中尽可能地并行化它。

假设我有一些任意的 function,它接受两个 arguments func(a,b) ,我想在 M 和 N 的所有组合上计算这个 function。

到目前为止我所做的是将索引“扁平化”为字典

idx_map = {} 
count = 0
for i in range(n):
    for j in range(m):
        idx_map[count] = (i,j)
        count += 1 

现在我的嵌套循环被展平了,我可以像这样使用它:

arr = []
for idx in range(n*m):
    i,j = idx_map[idx]
    arr.append( func(M[i], N[j]) )  

我可以将它与 Python 的内置多处理一起使用来并行化吗? 竞争条件应该不是问题,因为我不需要聚合 func 调用; 相反,我只想得到一些最终数组,它评估 M 和 N 中的所有func(a,b)组合。(因此异步行为和复杂性在这里不相关。)

实现此效果的最佳方法是什么?

我从this related question中看到,但我不明白作者试图说明什么。

if 1:   # multi-threaded
    pool = mp.Pool(28) # try 2X num procs and inc/dec until cpu maxed
    st = time.time()
    for x in pool.imap_unordered(worker, range(data_Y)):
        pass
    print 'Multiprocess total time is %4.3f seconds' % (time.time()-st)
    print

是的,您可以做到这一点,但是您每个 function 调用所做的工作量需要相当大才能克服流程的开销。

使用类似 numpy 的向量化通常更容易,如 Jérôme 先前所述。

我已经更改了您的代码,以便您可以观察使用多处理获得的速度。

随意更改 largNum 变量,以查看随着每个 function 调用的工作量增加,多处理的缩放比例如何变得更好,以及在低值下多处理实际上如何变慢。

from concurrent.futures import ProcessPoolExecutor
import time

# Sums n**2 of a+b
def costlyFunc(theArgs):
    a=theArgs[0]
    b=theArgs[1]
    topOfRange=(a+b)**2

    sum=0
    for i in range(topOfRange):
        sum+=i

    return sum
            
#changed to list
idx_map = []
largNum=200

# Your indicey flattening
for i in range(largNum):
    for j in range(largNum):
        idx_map.append((i,j))

我在单核版本中使用 map function 对列表中的每个元素调用 costlyFunc。 Python 的 concurrent.futures 模块也有类似的 map function,但是它将它分布在多个进程中。

if __name__ == "__main__":
    # No multiprocessing
    oneCoreTimer=time.time()
    result=[x for x in map(costlyFunc,idx_map)]
    oneCoreTime=time.time()-oneCoreTimer
    print(oneCoreTime," seconds to complete the function without multiprocessing")

    # Multiprocessing
    mpTimer=time.time()
    with ProcessPoolExecutor() as ex:
        mpResult=[x for x in ex.map(costlyFunc,idx_map)]
    mpTime=time.time()-mpTimer
    print(mpTime," seconds to complete the function with multiprocessing")

    print(f"Multiprocessing is {oneCoreTime/mpTime} times faster than using one core")

我希望这有帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM