安装profiler遇到的问题
line_profiler使用装饰器(@profile)标记需要调试的函数.用kernprof.py脚本运行代码,被选函数每一行花费的cpu时间以及其他信息就会被记录下来。
安装
首先是在linux上安装
pip3 install Cpython
pip3 install Cython git+https://github.com/rkern/line_profiler.git
可能会遇到的报错信息
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
需要更新setuptools才能生效
sudo pip install --upgrade setuptools
在windows安装可能遇到的问题
安装过程和linux的一致可能会遇到这样的报错
error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
需要安装更新Microsoft Visual
链接:百度网盘下载地址
提取码:70uj
测试
只需要在函数头部加上profile的装饰器
@profile
def read():
with open('/etc/samba/smb.conf')as f:
content = f.readlines()
for line in content:
print(line)
ret = re.search('/share/naslun10',line)
if ret:
print('ok')
read()
找到kernprof在本机上的执行路径(或者加到$PATH中)执行以下的命令
/usr/local/sbin/python-3.7/bin/kernprof -l -v test.py
执行结果如下
Total time: 0.004423 s
File: test.py
Function: read at line 4
Line # Hits Time Per Hit % Time Line Contents
==============================================================
4 @profile
5 def read():
6 1 122.0 122.0 2.8 with open('/etc/samba/smb.conf')as f:
7 1 120.0 120.0 2.7 content = f.readlines()
8 57 93.0 1.6 2.1 for line in content:
9 56 1398.0 25.0 31.6 print(line)
10 56 2568.0 45.9 58.1 ret = re.search('/share/naslun10',line)
11 56 105.0 1.9 2.4 if ret:
12 1 17.0 17.0 0.4 print('ok')
在Tltal time中列出了使用的总时间
time列表示每行使用的总时间
%time中显示了每行代码所占总用时
可以根据这些来判断代码中比较耗时的地方从而进行优化
在项目中如何使用呢?
我们可以将line_profiler的包直接导入
import line_profiler
def line_profile(func):
def inner_func(*args):
f_handler = open('line_profile.log','a')
profile = line_profiler.LineProfiler(func)
profile.enable()
ret = func(*args)
profile.disable()
profile.print_stats(f_handler)
return ret
return inner_func
这里我写了个装饰器,在需要检测的函数上添加这个装饰器就可以将检测结果实时写到文件中