代码性能至关重要,但有时难以弄清性能瓶颈的位置,python的
profile包可以解决这个问题并指导提升代码性能。
代码优化的前提是需要了解性能瓶颈在什么地方,程序运行的主要时间是消耗在哪里,对于比较复杂的代码可以借助一些工具来定位,python 内置了丰富的性能分析工具,如 profile, cProfile 与 hotshot 等。其中 Profiler 是 python 自带的一组程序,能够描述程序运行时候的性能,并提供各种统计帮助用户定位程序的性能瓶颈。Python 标准模块提供三种 profilers:cProfile, profile 以及 hotshot。
pycharm 专业版带有 profile 工具,vs code 等其他 ide 的 python 用户就需要自己调用profile了。
profile或cProfile
import cProfile
# or
import profiledef sub_fun():
sum = 0
for i in range(20):
sum += i
return sum
def fun():
sum = 0
for i in range(100):
sum += sub_fun()
return sum我们分析函数
fun的性能
cProfile.run('fun()')
# or
profile.run('fun()') 104 function calls in 0.000 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.000 0.000 <string>:1(<module>)
100 0.000 0.000 0.000 0.000 test.py:23(sub_fun)
1 0.000 0.000 0.000 0.000 test.py:30(fun)
1 0.000 0.000 0.000 0.000 {built-in method builtins.exec}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}参数名称 | 参数信息 |
|---|---|
ncalls | 表示函数调用的次数 |
tottime | 表示指定函数的总的运行时间,除掉函数中调用子函数的运行时间 |
percall | (第一个 percall)等于 tottime/ncalls |
cumtime | 表示该函数及其所有子函数的调用运行的时间,即函数开始调用到返回的时间 |
percall | (第二个 percall)即函数运行一次的平均时间,等于 cumtime/ncalls |
filename:lineno(function) | 每个函数调用的具体信息 |
如果需要将输出以日志的形式保存,只需要在调用的时候加入另外一个参数。 可以在当前文件夹存下日志信息到prof文件中。
profile.run(“fun()”, filename=”result.prof”)如果不想在程序中调用profile库使用,可以在命令行使用命令。
python -m cProfile test.pypython -m cProfile -o result.prof test.pypstats 读取prof文件中的日志import pstats
p=pstats.Stats('result.prof')
p.sort_stats('time').print_stats()比较推荐的是使用
snakeviz可视化代码运行时间 官网:https://jiffyclub.github.io/snakeviz/
snakevizpip install snakeviz运行Python代码的同时用cProfile保存运行时间数据
注意:要用
cProfile,使用profile会导致snakeviz无法读取日志 相关错误信息:
Traceback (most recent call last):
File ".../site-packages/tornado/web.py", line 1413, in _execute
result = method(*self.path_args, **self.path_kwargs)
File ".../site-packages/snakeviz/main.py", line 30, in get
table_rows=table_rows(s), callees=json_stats(s))
File ".../site-packages/snakeviz/stats.py", line 65, in json_stats
(keyfmt(*ck), list(cv)) for ck, cv in stats.stats[k][-1].items())
File ".../site-packages/snakeviz/stats.py", line 65, in <genexpr>
(keyfmt(*ck), list(cv)) for ck, cv in stats.stats[k][-1].items())
TypeError: 'int' object is not iterablesnakeviz作用于我们需要观察的日志文件:snakeviz result.prof