進行分析的輔助類
Python中提供了很多接口方便我們能夠靈活進行性能分析室囊,包括cProfile模塊中的Profile類和pstat模塊中的Stats類。
cprofile簡介
--cprofile是一種確定性分析器瘟栖,只測量CPU時間,并不關心內(nèi)存的消耗情況和其他與內(nèi)存相關聯(lián)的信息
--它是基于Isprof的用C語言實現(xiàn)的擴展應用,運行開銷比較合理爷耀,適合分析運行時間較長的程序
Profile類:
--enable(): 開始進行性能分析并收集數(shù)據(jù)
--disableI(): 停止性能分析
--create_stats(): 停止收集數(shù)據(jù),并為已經(jīng)收集的數(shù)據(jù)創(chuàng)建stats對象
--print_stats():創(chuàng)建stats對象并打印分析結(jié)果
--dump_stats(filename): 把當前性能分析的內(nèi)容寫入文件filename中
--runcall(func, *args, **kwargs): 收集被調(diào)用函數(shù)func的性能分析信息
pstats簡介
--用來分析cProfile輸出的文件內(nèi)容
--pstas模塊為開發(fā)者提供了Stats類拍皮,可以讀取和操作stats文件
Stats類:
(Stats類可以接受stats文件名歹叮,也可以直接接受cProfile.Profile對象作為數(shù)據(jù)源。)
--strip_dirs(): 刪除報告中所有函數(shù)文件名的路徑信息
--dump_stats(filename): 把stats中的分析數(shù)據(jù)寫入文件(也可以寫成cProfile.Profile.dump_stats())
--sort_stats(*keys): 對報告列表進行排序铆帽,函數(shù)會一次按照傳入的參數(shù)排序
--reverse_order(): 逆反當前的排序
--print_stats(*restrictions): 把信息打印到標準輸出咆耿。*restrictions用于控制打印結(jié)果的形式,比如(10,1.0爹橱,".*.py.*")表示打印所有py文件的信息的前10行結(jié)果
打印數(shù)據(jù)的解讀:
--第一行表示運行這個函數(shù)一共使用0.043秒萨螺,執(zhí)行了845次函數(shù)調(diào)用
--第二行表示結(jié)果是按什么順序排列的(這里表示按照調(diào)用次數(shù)來進行排列的)
--ncalls: 表示函數(shù)調(diào)用的次數(shù)(有兩個數(shù)值表示有遞歸調(diào)用,總調(diào)用次數(shù)/原生調(diào)用次數(shù))
--tottime: 函數(shù)內(nèi)部調(diào)用時間(不包括他自己調(diào)用的其他函數(shù)時間)
? ? eg:funA():?
? ? ? ? ? ? ? ? funB() 得到tottime = funA()執(zhí)行的時間-funB()執(zhí)行的時間
--percall: tottime/ncalls
--cumtime: 表示累計調(diào)用時間(函數(shù)執(zhí)行玩的總時間),它包含了函數(shù)自己內(nèi)部調(diào)用的函數(shù)時間
--filename:lineno(function): 函數(shù)所在的文件屑迂,行號浸策,函數(shù)名稱
一個例子,使用裝飾器對一個函數(shù)進行分析
import cProfile
import pstats
import functools
def do_cProfile(do=False, order='tottime'):
????????def wrapper(func):
????????????????@functools.wraps(func)
????????????????def profiled_func(*args, **kwargs):
????????????????if do:
????????????????????profile = cProfile.Profile()
????????????????????profile.enable()
????????????????????result = func(*args, **kwargs)
????????????????????profile.disable()
????????????????????#profile.print_stats()
? ? ? ? ? ? ????????ps = pstats.Stats(profile).sort_stats(order).strip_dirs()
????????????????????ps.print_stats()
????????????????else:
????????????????result = func(*args, **kwargs)
????????????????return result
????????return profiled_func
return wrapper
上面的函數(shù)do_cProfile(do=False, order='tottime')是一個帶參數(shù)的裝飾器惹盼,通過do的值來進行性能分析的開關控制庸汗,通過order的值來選擇輸出結(jié)果按照什么方式進行排序。
比如我們對函數(shù)A和函數(shù)B進行性能分析
from profile_decorator import do_cProfile
@do_cProfile(True)
def funA():...
@do_cProfile(True, calls)
def funB():...
如果不給裝飾器傳入?yún)?shù)的話就是默認的False和tottime
參考連接:
https://zhuanlan.zhihu.com/p/24495603
https://blog.csdn.net/weixin_40304570/article/details/79459811