Python函数中大任务的并行化

问题描述 投票:0回答:1

我有一个函数想在 Python3 中进行多线程/并行化。

calculate(c1,c2)
函数需要很长时间来计算,因此我想将它并行化,以加速更大数据集的计算。

def multi_thread_func(df):
    cols = df.cols
    i = 0
    a = np.zeros((len(cols)*len(cols)))
    for c1 in cols:
        for c2 in cols:
            res = calculate(c1,c2)
            a[i] = None if res is None else res
            i += 1
    return res

我试过在 Python 中使用 concurent.futures 但它似乎不起作用。

python parallel-processing python-multiprocessing python-multithreading concurrent.futures
1个回答
0
投票
def multi_thread_func(df):
    length = len(df.cols)
    a = np.zeros((length * length))

    with multiprocessing.Pool() as pool:
        i = 0
        for value in pool.starmap(calculate, itertools.product(range(length), repeat=2)):
            a[i] = value
            i += 1

    return a
© www.soinside.com 2019 - 2024. All rights reserved.