首页 > 解决方案 > 为什么 concurrent.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.05 秒(即 100,000 次迭代)。

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

标签: pythonthreadpoolexecutorconcurrent.futures

解决方案


推荐阅读