为什么parallel.futures中的ThreadPoolExecutor运行时间比非并行运行时间长?

问题描述

我有一个使用 concurrent.futures / ThreadPoolExecutor 的并行程序:

from concurrent.futures import ThreadPoolExecutor as PoolExecutor
import numpy as np,timeit
start = timeit.default_timer()
n = 2

def f(samp):
    t = samp ** 10
        
samps = np.random.uniform(low=0,high=1,size=(100000,))

with PoolExecutor(max_workers=n) as executor:
    for _ in executor.map(f,samps):
        pass

print(f"time: {timeit.default_timer() - start}")

大约需要3秒钟才能运行。

如果我按顺序运行它而不进行并行化,即:

for samp in samps: t = samp ** 10

运行大约需要0.05s(即100,000次迭代)。

为什么并行化版本需要这么长的时间。注意增加 max_workers 也会增加运行时间。另外,这可能是一个愚蠢的代码示例,但是我的原始代码正在处理800个文件-它比顺序版本花费的时间更长。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)