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:執行一段代碼時間消耗比例。
memory_profiler
作用
監控代碼每一行的內存消耗。
安裝
pip install memory_profiler
使用
from memory_profiler import profile
@profile
def func():
print "vvtest"
使用注意:
使用裝飾器@profile的時候,就不能與line_profiler同時使用。
原因是line_profiler裏也有同名裝飾器@profile
使用memory_profiler時候可以結合matplotlib使用,可以以圖形化的方式直觀的查看內存的使用情況(本人在cetntos上沒有跑成功過),我覺得這個大佬寫得挺好的,轉鏈https://zhuanlan.zhihu.com/p/121003986
pip install matplotlib
mprof plot
mprof plot mprofile_xxxxx.dat
使用的時候有可能會報_tkinter不存在,那我只能說你需要重裝python的解釋器或重新編譯一次解釋器。重裝python解釋器之前安裝好的依賴包需要重裝,成本挺高的。
解決方案可以參考: