You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何Joblib并行处理时{built-in method time.sleep}成为性能瓶颈?

问题

在Python应用中使用Joblib执行并行任务时,性能分析发现最慢的操作是{built-in method time.sleep},移除Joblib并行处理后该问题消失,求解释原因。

简化代码

from joblib import Parallel, delayed

def my_function(x):
    # Some computation
    return x * x

results = Parallel(n_jobs=2)(delayed(my_function)(i) for i in range(10))

性能分析输出

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
    17153  209.317    0.012  209.317    0.012 {built-in method time.sleep}
      588    0.835    0.001    0.835    0.001 {method 'poll' of 'select.poll' objects}
原因解释
  • Joblib调度机制的固有开销:Joblib管理并行进程时,会通过time.sleep实现进程间同步、空闲等待或状态轮询。这些调度逻辑本身会产生额外耗时。
  • 任务粒度太细放大开销:你的示例任务只是简单的乘法运算,执行时间远短于Joblib创建进程、分配任务、回收进程的时间。此时调度逻辑的占比被急剧放大,频繁的time.sleep调用累计出了大量耗时。
  • 串行执行无调度成本:移除Joblib后,代码在单进程串行运行,不需要处理多进程间的调度、同步逻辑,自然不会触发这些time.sleep调用,也就没有了这部分额外耗时。

内容的提问来源于stack exchange,提问作者Mykola Zotko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 15:17:32