介绍
profile和line_profiler两个模块都是性能分析工具。有时候需要找到代码中运行速度较慢处或瓶颈,可以通过这两模块实现,而不再使用time计时。
line_profiler模块可以记录每行代码的运行时间和耗时百分比。
安装
输入以下命令安装即可
pip install line_profiler
使用
方法1 :生成一个Line_profiler类(推荐)
简单版本
from line_profiler import LineProfiler
def do_stuff(numbers):
s = sum(numbers)
l = [numbers[i] / 43 for i in range(len(numbers))]
m = ['hello' + str(numbers[i]) for i in range(len(numbers))]
if __name__ == '__main__':
number = [1,2,3,4,5,6]
p = LineProfiler()
p_wrap = p(do_stuff)
p_wrap(number)
p.print_stats() # 控制台打印相关信息
p.dump_stats('saveName.lprof') # 当前项目根目录下保存文件
输出结果:
"D:\Program Files\Anaconda3\envs\tensorflow2.3\python.exe" "C:/Users/admin/Desktop/xxxx/temp.py"
Timer unit: 1e-07 s
Total time: 1.08e-05 s
File: C:/Users/admin/Desktop/GPflowMPC_cui _contract - profile/temp.py
Function: do_stuff at line 193
Line # Hits Time Per Hit % Time Line Contents
==============================================================
193 def do_stuff(numbers):
194 1 21.0 21.0 19.4 s = sum(numbers)
195 1 45.0 45.0 41.7 l = [numbers[i] / 43 for i in range(len(numbers))]
196 1 42.0 42.0 38.9 m = ['hello' + str(numbers[i]) for i in range(len(numbers))]
多函数调用
当你需要调用不止一个函数的时候,就可以使用add_function函数去添加额外需要监控的函数
from line_profiler import LineProfiler
def second_function():
# just for test
i = 5
pass
def do_stuff(numbers):
s = sum(numbers)
l = [numbers[i] / 43 for i in range(len(numbers))]
m = ['hello' + str(numbers[i]) for i in range(len(numbers))]
for i in range(5):
second_function()
if __name__ == '__main__':
number = [1,2,3,4,5,6]
p = LineProfiler()
p.add_function(second_function)
p_wrap = p(do_stuff)
p_wrap(number)
p.print_stats()
p.dump_stats('saveName.lprof')
输出结果
"D:\Program Files\Anaconda3\envs\tensorflow2.3\python.exe" "C:/Users/admin/Desktop/xxxx/temp.py"
Timer unit: 1e-07 s
Total time: 2.4e-06 s
File: C:/Users/admin/Desktop/GPflowMPC_cui _contract - profile/temp.py
Function: second_function at line 193
Line # Hits Time Per Hit % Time Line Contents
==============================================================
193 def second_function():
194 # just for test
195 5 14.0 2.8 58.3 i = 5
196 5 10.0 2.0 41.7 pass
Total time: 2.44e-05 s
File: C:/Users/admin/Desktop/GPflowMPC_cui _contract - profile/temp.py
Function: do_stuff at line 198
Line # Hits Time Per Hit % Time Line Contents
==============================================================
198 def do_stuff(numbers):
199 1 22.0 22.0 9.0 s = sum(numbers)
200 1 48.0 48.0 19.7 l = [numbers[i] / 43 for i in range(len(numbers))]
201 1 45.0 45.0 18.4 m = ['hello' + str(numbers[i]) for i in range(len(numbers))]
202 6 32.0 5.3 13.1 for i in range(5):
203 5 97.0 19.4 39.8 second_function()
方法2:使用装饰器@profile
在需要检测的函数上面添加@profile
装饰符号, (此时调包是调用profile 而不是line_profiler)。
在命令行中使用kernprof -l -v test.py
启动,结束会在窗口打印逐行信息以及生成一个lprof文件。 与方法1 相似。
问题在于每次不在使用profile 查看性能时,需要将函数上的装饰类注释掉
读取lprof 文件: 进入当前目录后,在命令行中使用
python -m line_profiler saveName.lprof
# saveName.lprof 读取指定文件
资料来源 https://blog.csdn.net/weixin_44613728/article/details/120411325
评论 (0)