You need to enable JavaScript to run this app. Python Multiprocessing多进程运行未达预期提速效果问题排查
优惠活动
大模型
产品
解决方案
定价
更多

Python Multiprocessing多进程运行未达预期提速效果问题排查

问题排查及修复

核心错误点

  • executor.submit() 调用时参数传递错误:你写的executor.submit(new_func()) 中new_func()带了括号,会直接在主线程同步执行该函数,执行完成后才会把返回值(None)传给submit方法,本质上没有把函数提交给进程池异步执行,5次调用依然是串行执行,所以耗时和同步执行接近。
  • 补充:你的new_func内部循环逻辑存在无效操作,每次循环都会将count重置为0再+1,不过这个问题不影响耗时统计结果。

修复后的代码

import time
import concurrent.futures

def new_func():
    count = 0
    for _ in range(100_000_000):
        count += 1
    print("Finished Processing")

# Windows系统必须加这行,避免多进程无限spawn报错
if __name__ == '__main__':
    start = time.perf_counter()
    # 同步执行
    for _ in range(5):
        new_func()
    time1 = time.perf_counter()
    normal_time = time1 - start
    print(f"the normal time is: {normal_time}")

    # 多进程执行
    with concurrent.futures.ProcessPoolExecutor() as executor:
        # 提交任务时只传函数名,不加括号,不要直接调用函数
        tasks = [executor.submit(new_func) for _ in range(5)]
        # 等待所有任务执行完成,上下文管理器退出时也会自动等待,加了逻辑更明确
        for future in concurrent.futures.as_completed(tasks):
            pass
    time2 = time.perf_counter()
    multi_time = time2 - time1
    print(f"the multi-time is {multi_time}")

修复后效果

如果你的CPU是N核,多进程执行耗时会降到同步执行的1/N左右(排除进程创建的小额开销),符合预期的加速效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 20:48:01