python代码运行慢,也是服从二八定律的,也就是20%的代码运行时间占比超过80%。
在优化代码时,你可以手动使用time.time()来对每行代码进行计时,但是还是那句话:不够优雅。
那么,有没有优雅、简单、功能强大的代码性能分析器呢?
答案是有的:LineProfiler。line_profiler是Python的一个第三方库,其功能时基于函数的逐行代码分析工具。通过该库,可以对目标函数(允许分析多个函数)进行时间消耗分析,便于代码调优。
你可以使用pip来安装它,之后就可以按照官方教程来使用。
pip install line_profiler
我为了更加方便的使用LineProfiler,给它写了个装饰器,使用时只需要两行代码即可分析一个函数的详细耗时情况(完整示例代码链接:github链接):
def performance_test(exit_flag=True):
def func_layer(func):
def wrapper(*args, **kwargs):
from line_profiler import LineProfiler
lp = LineProfiler()
lpw = lp(func) # function need to be analysed
func_output = lpw(*args, **kwargs) # the parameters of target function
lp.print_stats() # print analyse results
if exit_flag:
exit()
return func_output
return wrapper
return func_layer
在需要分析的函数前面加上@performance_test(True),之后照常运行代码即可,示例如下:
import performance_test
@performance_test()
def func_test():
a = [i for i in range(10000)]
b = sum(a)
return b
然后运行就会在terminal里面打印出每行代码的耗时,清晰明了。
Hits表示调用了几次;Time表示该行总耗时,单位是微秒;Per Hit就是该行单次耗时;%Time就是时间占比,一般看这个时间占比来查看哪句话需要优化。
Timer unit: 1e-06 s
Total time: 0.001297 s
File: /home/longer/Nutstore Files/Longer/working/mf/signal-screener/performance_test.py
Function: func at line 30
Line # Hits Time Per Hit % Time Line Contents
==============================================================
30 @performance_test()
31 def func():
32 1 1223.0 1223.0 94.3 a = [i for i in range(10000)]
33 1 73.0 73.0 5.6 b = sum(a)
34 1 1.0 1.0 0.1 return b
line_profile还有许多其他功能,可以查看官方文档。
完整示例代码链接:github链接