import cProfile
def simple_function():
total = 0
for i in range(1000000):
total += i
return total
cProfile.run('simple_function()')
解读分析结果
- 调用次数:在分析结果中,每一行记录的
ncalls
列代表函数的调用次数。例如 1 0.000 0.000 0.000 0.000 <string>:1(<module>)
中 1
就是 <string>:1(<module>)
这个函数(其实这里是整个脚本入口,类似main函数的概念)的调用次数。如果一个函数在其他函数内部被循环调用,这里的调用次数就会相应增加。
- 总运行时间:
tottime
列表示该函数自身运行的总时间,不包含它调用其他函数的时间。比如 0.025 0.025 0.000 0.000 {method 'range' of 'builtins.list' objects}
中的 0.025
就是 range
这个函数自身运行的总时间。而 cumtime
列表示该函数及其所有子函数运行的总时间。例如 0.025 0.025 0.025 0.025 simple_function
中 0.025
是 simple_function
及其调用的所有函数(这里是 range
等)运行的总时间。
- 每次调用的平均时间:对于
tottime
的平均时间,计算方式是 tottime / ncalls
,对于 cumtime
的平均时间,计算方式是 cumtime / ncalls
。例如在 1 0.025 0.025 0.025 0.025 simple_function
中,tottime
的平均时间是 0.025 / 1 = 0.025
,cumtime
的平均时间也是 0.025 / 1 = 0.025
。通过这些平均时间可以直观了解每次调用该函数大概需要花费的时间,方便定位性能瓶颈函数。