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

Python多进程perf_counter返回超大计时值问题求助(Mac)

问题原因与解决方法
  • 问题本质:你直接调用time.perf_counter()得到的是该函数基准时间点到当前的累计时长,并非任务执行的耗时。perf_counter()的返回值是从系统某个固定起点(比如系统启动时刻)开始计算的总时间,不是单次任务的运行时间。

  • 修正方案:需要在任务开始前记录起始时间,任务结束后记录结束时间,两者的差值才是实际耗时。

修正后的代码:

import time
from multiprocessing import Process

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

def main():
    start_time = time.perf_counter()  # 记录任务开始时间
    a = Process(target=counter, args=(100000000,))
    a.start()
    a.join()
    end_time = time.perf_counter()  # 记录任务结束时间
    print("finished in", end_time - start_time, "seconds")

if __name__ == '__main__':
    main()

运行这段代码后,输出的耗时就会和实际感知的4-5秒一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 06:02:09