如何通过cProfile获取程序及指定函数的墙上时间?
用cProfile获取墙上时间的方法
首先明确几个核心点:
- cProfile默认使用进程CPU时间(只统计当前进程占用CPU的时长,不包含等待IO、休眠、其他进程抢占CPU的时间),并非墙上时间(实际流逝的实时时间)。
tottime、cumtime这类指标的时间类型完全取决于你用的计时器:默认是CPU时间,切换到墙上时间计时器后,这些指标就对应实际流逝的时间。
1. 适配命令行场景的墙上时间 profiling 方案
因为python3 -m cProfile本身不支持直接指定计时器参数,你可以写一个简单的包装脚本,强制使用高精度墙上时间计时器(time.perf_counter是Python官方推荐的墙上时间工具):
创建一个名为profile_walltime.py的脚本:
import cProfile import sys import time def run_profile(): # 初始化profiler,指定用墙上时间计时器 profiler = cProfile.Profile(timer=time.perf_counter) # 运行目标自动生成的脚本 profiler.run(f"exec(open('{sys.argv[1]}').read())") # 直接打印统计结果,也可以替换为dump_stats保存到文件后续分析 profiler.print_stats() if __name__ == "__main__": if len(sys.argv) < 2: print("Usage: python profile_walltime.py your_auto_generated_script.py") sys.exit(1) run_profile()
之后用这个脚本替代python3 -m cProfile运行你的程序:
python profile_walltime.py your_auto_generated_script.py
如果需要保存结果到文件做后续分析,把脚本里的profiler.print_stats()改成profiler.dump_stats("profile_results.dat"),之后可以用pstats模块查看:
python -m pstats profile_results.dat
2. 如何查看特定函数的墙上时间
不管是直接打印结果还是分析保存的统计文件,都能快速筛选目标函数的时间:
- 在
pstats交互模式下,输入sort cumulative按累计时间排序,再输入print your_target_function,就能看到该函数的tottime(函数自身消耗的时间)和cumtime(函数加子函数的总消耗时间),此时这两个值都是墙上时间。 - 直接在控制台过滤的话,用grep(Linux/macOS)或findstr(Windows):
python profile_walltime.py your_script.py | grep "your_specific_function"
3. 再明确:tottime是不是墙上时间?
答案是取决于你使用的计时器:
- 默认场景下,cProfile用进程CPU时间,
tottime代表该函数自身消耗的CPU时间(不包含子函数调用的时间)。 - 当你切换到墙上时间计时器后,
tottime就变成了该函数自身运行的实际流逝时间(包括等待IO、休眠等非CPU工作的时长)。
内容的提问来源于stack exchange,提问作者joel
相关产品推荐
相关产品推荐

