python - 为什么 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 个文件 - 它也比顺序版本花费了更长的时间。
解决方案
推荐阅读
- c# - 抛出的异常:带有 Google Speech API 的 System.Private.CoreLib.dll 中的“Grpc.Core.RpcException”
- entity-framework - 不使用 OnConfiguring(DbContextOptionsBuilder optionsBuilder) 无法构造 DbContext
- coq - IndProp:re_not_empty_correct
- angular - 如何将指纹扫描仪与前端 Angular 和后端 .NET (c#) Web App 集成
- c# - 使用 nuget pack 解决具有一些不安全代码的解决方案时出现错误
- javascript - 如何在 React/Node 中按顺序处理 api 调用承诺
- typescript - 类型“布尔”不可分配给“假”类型
- wpf - 如何正确设置此按钮与父 ListView ItemsControl 的绑定?
- log4j2 - 清除日志文件后,Log4j2 停止记录到日志文件
- postgresql - 是否有一个命令可以在 Postgresql 中为我提供逻辑查询计划概述?