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