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

如何通过cProfile获取挂钟时间?

如何用cProfile获取挂钟时间(Wall-Clock Time)

好问题!我来帮你理清cProfile的时间统计逻辑,以及怎么拿到你需要的挂钟时间:

先明确核心概念

  • cProfile默认使用的是进程CPU时间(只统计代码占用CPU执行的时间,不包含等待IO、睡眠、网络请求这些空闲时间),不是挂钟时间(从程序启动到结束的实际流逝时间)。
  • tottime和cumtime都不是挂钟时间:
    • tottime是函数自身(不包含调用子函数)消耗的CPU时间
    • cumtime是函数加上它调用的所有子函数总共消耗的CPU时间

用命令行python3 -m cProfile获取挂钟时间的方法

根据你的Python版本,操作略有不同:

Python 3.8及以上版本(推荐)

Python 3.8给cProfile加了--timer命令行参数,直接指定用挂钟时间即可:

# 直接在终端输出统计结果
python3 -m cProfile --timer=wallclock your_script.py

# 或者将结果保存到stats文件,方便后续用pstats分析
python3 -m cProfile --timer=wallclock -o profile_results.stats your_script.py

Python 3.7及以下版本

没法直接通过命令行参数指定,需要借助环境变量PYTHONPROFILETIMER来替换默认计时器,指定用time.time()(返回挂钟时间):

  • Linux/macOS终端:
PYTHONPROFILETIMER=time.time python3 -m cProfile your_script.py
  • Windows CMD:
set PYTHONPROFILETIMER=time.time && python3 -m cProfile your_script.py
  • Windows PowerShell:
$env:PYTHONPROFILETIMER='time.time'; python3 -m cProfile your_script.py

查看特定函数的挂钟时间

如果把结果保存到了stats文件,你可以用pstats模块过滤特定函数:

import pstats

# 加载统计结果
stats = pstats.Stats('profile_results.stats')
# 按挂钟时间排序,然后打印指定函数的统计信息
stats.sort_stats('time').print_stats('your_target_function')

这样就能精准看到目标函数以及整个程序的挂钟时间消耗啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 09:27:37