python line_profiler 代码性能分析

作用

按行分析代码性能消耗,主要是时间

安装

pip install line_profiler
pip install wrapt

使用

写一个单独的装饰器,代码如下:

import wrapt
from line_profiler import LineProfiler
lp = LineProfiler()


def lineprofile_wrapper():
    @wrapt.decorator
    def wrapper(func,instance,args,kwargs):
        global lp
        lp_wrapper = lp(func)
        res = lp_wrapper(*args,**kwargs)
        lp.print_stats()
        return res
    return wrapper

写一个测试demo

@lineprofile_wrapper()
def test():
    print ('vvtest')
    a = sum([1, 2, 3])
    b = sum([1, 2, 3])
    return sum([a,b])

if __name__ == '__main__':
    test();

执行结果:

Timer unit: 1e-06 s

Total time: 2e-05 s
File: /vv/line_profiler/demo.py
Function: test at line 5

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
     5                                           @lineprofile_wrapper()
     6                                           def test():
     7         1         16.0     16.0     80.0      print ('vvtest')
     8         1          3.0      3.0     15.0      a = sum([1, 2, 3])
     9         1          1.0      1.0      5.0      b = sum([1, 2, 3])
    10         1          0.0      0.0      0.0      return sum([a,b])

可以看到每一行,只要被执行,就会有消耗的时间与占比。没有被执行的会为空

  • Line:文件中的行号。
  • Hits:性能分析时代码执行的次数。
  • Time:一段代码执行的总时间,由计数器决定。(时间单位在【执行结果】里的Timer unit)
  • Per Hit:执行一段代码平均消耗时间。(时间单位在【执行结果】里的Timer unit)
  • % Time:执行一段代码时间消耗比例。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章