python学习笔记10:分析程序性能cProfile
目录
- 1. 一个函数
- 2. 在脚本中测试性能:
- 3. 在命令行测试性能:
- 4. 报告中的参数说明
1. 一个函数
>>> import random
>>> lst = [random.random() for i in range(10000)]
>>> def f1(lst0):
... lst1 = sorted(lst0)
... lst2 = [i for i in lst1 if i<0.5]
... lst3 = [i*i for i in lst2]
... return lst3
2. 在脚本中测试性能:
>>> import cProfile
>>> cProfile.run('f1(lst)')
7 function calls in 0.005 seconds
Ordered by: standard name
ncalls tottime precall cumtime precall filename:lineno(function)
1 0.000 0.000 0.861 0.861 :1(f1)
1 0.118 0.118 0.118 0.118 :3()
1 0.078 0.078 0.078 0.078 :4()
1 0.027 0.027 0.888 0.888 :1()
1 0.000 0.000 0.888 0.888 {built-in method builtins...}
1 0.665 0.665 0.665 0.665 {built-in method builtins...}
1 0.000 0.000 0.000 0.000 {method 'disable' of ...}
3. 在命令行测试性能:
$ python –m cProfile test.py
4. 报告中的参数说明
| 参数 | 说明 |
|---|---|
| ncalls | 表示函数调用的次数; |
| tottime | 表示指定函数的总的运行时间,除掉函数中调用子函数的运行时间; |
| percall(第一个percall) | 等于 tottime/ncalls; |
| cumtime | 表示该函数及其所有子函数的调用运行的时间,即函数开始调用到返回的时间; |
| percall(第二个percall) | 函数运行一次的平均时间,等于 cumtime/ncalls; |
| filename:lineno(function) | 每个函数调用的具体信息; |