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:執行一段代碼時間消耗比例。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章