Python3逐行分析代码运行时间
Python3 有一个很好用的第三方库叫 line_profiler 可以分析每行代码的运行时间及占比
安装
pip install line_profiler
使用
# @Coding: utf-8 # @Time: 2021/8/5 3:54 下午 from line_profiler import LineProfiler def test(num1, num2): num3 = num1 ** num2 print(num3) if __name__ == '__main__': # 正常调用 # test(2, 3) # 分析时间 lp = LineProfiler() lp_wrapper = lp(test) lp_wrapper(2, 3) lp.print_stats()
结果
8 Timer unit: 1e-06 s Total time: 3.9e-05 s File: /Users/wangwenjie/code/test/1111111.py Function: test at line 8 Line # Hits Time Per Hit % Time Line Contents ============================================================== 8 def test(num1, num2): 9 1 8.0 8.0 20.5 num3 = num1 ** num2 10 1 31.0 31.0 79.5 print(num3) Process finished with exit code 0
但是在正常的函数中会出现调用其他的函数,这时我们可以使用 add_function()方法来进行调用函数的分析, 如下
# @Coding: utf-8 # @Time: 2021/8/5 3:54 下午 from line_profiler import LineProfiler def test(num1, num2): num3 = num1 ** num2 num4 = max_num(num1, num2) print(num3, num4) def max_num(num1, num2): if num1 >= num2: return num1 return num2 if __name__ == '__main__': # 正常调用 # test(2, 3) # 分析时间 lp = LineProfiler() lp.add_function(max_num) lp_wrapper = lp(test) lp_wrapper(2, 3) lp.print_stats()
结果:
/usr/bin/python3 /code/test/line_profiler_use.py 8 3 Timer unit: 1e-06 s Total time: 5e-05 s File: /Users/wangwenjie/code/test/line_profiler_use.py Function: test at line 8 Line # Hits Time Per Hit % Time Line Contents ============================================================== 8 def test(num1, num2): 9 1 8.0 8.0 16.0 num3 = num1 ** num2 10 1 4.0 4.0 8.0 num4 = max_num(num1, num2) 11 1 38.0 38.0 76.0 print(num3, num4) Total time: 2e-06 s File: /Users/wangwenjie/code/test/line_profiler_use.py Function: max_num at line 14 Line # Hits Time Per Hit % Time Line Contents ============================================================== 14 def max_num(num1, num2): 15 1 1.0 1.0 50.0 if num1 >= num2: 16 return num1 17 1 1.0 1.0 50.0 return num2 Process finished with exit code 0