性能调优主要包括时间的优化和内存的优化.要做时间的优化首先就要统计时间,python本身提供了一个描述程序时间性能的类cProfile.
如要获取func函数所耗用的时间,可以使用如下代码
import cProfile
cProfile.run('func()')
cProfile.run('func()')
如果需要知道一个python文件运行的时间,可以在命令行下使用如下命令
python -m cProfile myscript.py
通常输出如下:
代码
3 function calls in 0.446 CPU seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.446 0.446 <string>:1(<module>)
1 0.446 0.446 0.446 0.446 wordcounter.py:7(__init__)
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.446 0.446 <string>:1(<module>)
1 0.446 0.446 0.446 0.446 wordcounter.py:7(__init__)
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
ncalls表示函数调用的次数
tottime表示指定函数消耗的时间
percall表示函数每次调用的平均耗时,tottime/ncalls
cumtime表示该函数及其所有子函数的调用耗时,就是从函数开始调用到返回的时间
第二个percall为cumtime/primitive calls的值
filename:lineno(function)表示每个函数所在的位置