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

Python多进程场景下time.perf_counter返回异常大秒数的原因是什么?

异常值产生原因
  • 核心问题是你对time.perf_counter()的功能理解有误:该接口返回的是系统开机启动到当前调用时刻的累计总秒数,不是你指定代码段的执行耗时。你看到的37724左右的数值,本质是你的操作系统已经开机运行了约10.5小时(37724÷3600≈10.48),和你代码的实际运行耗时没有直接关系。
  • 你调整计数参数到10亿后看到的数值变大,两次输出的差值部分才是你的代码真实耗时:比如两次输出分别为37724和37784,就说明10亿次计数的任务实际跑了60秒。
正确的耗时统计写法

你需要在任务启动前记录一次time.perf_counter()的起始值,待任务全部结束后用结束值减去起始值,才能得到准确的代码段执行耗时,修正后代码如下:

from multiprocessing import Process
import time


def counter(num):
    count = 0
    while count < num:
        count += 1

def main():
    # 先记录起始时间戳
    start = time.perf_counter()
    a = Process(target=counter, args=(500,))
    b = Process(target=counter, args=(500,))

    a.start()
    b.start()

    a.join()
    b.join()
    # 结束时间戳减起始时间戳得到实际耗时
    print("finished in", time.perf_counter() - start, " seconds.")

if __name__ == "__main__":
    main()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 06:06:03