为具有多个输入和输出的功能并行化for循环

时间:2019-09-09 14:02:31

标签: python parallel-processing multiprocessing

我已经阅读了几篇有关使用Python进行多处理的文章,但是我不清楚如何将它们用于解决我的问题(我有多个输入和输出)。大多数可用示例都考虑了具有简单结构的单个输出函数。

这是Python中的代码:

import numpy as np

n = 1000
i1 = np.random.random(n)
i2 = np.random.random(n)
i3 = np.random.random(n)
i4 = np.random.random(n)

o1 = np.zeros(n)
o2 = np.zeros(n)
o3 = np.zeros(n)

def fun(i1,i2,i3,i4):
    o1 = i1 + i2 + i3 + i4
    o2 = i2*i3 - i1 + i4
    o3 = i1 - i2 + i3 + i4

    if o1 < o2:
        o1 = o2
    else:
        o2 = o1

    while o1 + o2 > o3:
        o3 = o3 + np.random.random()

    return o1,o2,o3

for i in range(n):  # I want to parallellise this loop
    o1[i],o2[i],o3[i] = fun(i1[i],i2[i],i3[i],i4[i])

我只是在寻找一种并行化for循环的方法。我该怎么做?

1 个答案:

答案 0 :(得分:0)

我将使用生成器来组合您的输入列表i1至i4。您的数学函数fun将返回一个列表对象。现在,我有一个参数作为输入(生成器),并有一个对象作为输出(列表)。我已经尝试过下面的代码,并且可以正常工作。

您可以在fun函数中添加一个sleep命令,以查看使用多个进程时的速度增益。否则,您的fun函数太简单了,无法真正从多处理中受益。

import numpy as np
from multiprocessing import Pool

n = 1000
i1 = np.random.random(n)
i2 = np.random.random(n)
i3 = np.random.random(n)
i4 = np.random.random(n)

def fun(a):
    o1 = a[0] + a[1] + a[2] + a[3]
    o2 = a[1]*a[2] - a[0] + a[3]
    o3 = a[0] - a[1] + a[2] + a[3]

    if o1 < o2:
        o1 = o2
    else:
        o2 = o1

    while o1 + o2 > o3:
        o3 = o3 + np.random.random()

    return [o1,o2,o3]

# a generator that fills the Pool input
def conc(lim):
    n = 0
    while n < lim:
        yield [i1[n], i2[n], i3[n], i4[n]]
        n += 1


if __name__ == '__main__':
    numbers = conc(n)
    with Pool(5) as p:
        print(p.map(fun, numbers))