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

使用cProfile分析Python脚本:求解读性能分析结果

Python脚本cProfile性能分析记录

最近我用cProfile给Python小脚本做性能分析,写了个简单的测试代码,跑出来的结果整理如下:

测试脚本代码

def foo(): 
    for i in range(100000): 
        print i
def bar(): 
    for i in range(100): 
        print "bar"*i
foo()
bar()

执行性能分析的命令

我用这条命令启动性能分析:

python -m profile script.py

cProfile输出结果

执行后得到的性能数据如下:

7 function calls in 0.136 seconds
Ordered by: standard name

ncalls tottime percall cumtime percall filename:lineno(function)
2 0.000 0.000 0.000 0.000 :0(range)
1 0.000 0.000 0.000 0.000 :...

结果字段简单说明

给刚接触cProfile的朋友解释下核心字段:

  • ncalls:对应函数被调用的总次数
  • tottime:函数自身执行消耗的时间(不包含它调用其他函数的耗时)
  • percall(第一个):tottime除以ncalls,即单次调用的平均自身耗时
  • cumtime:函数加上它调用的所有子函数的总耗时
  • percall(第二个):cumtime除以ncalls,即单次调用的平均总耗时

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:48:27