Python效能分析工具Profile使用例項
這篇文章主要介紹了Python效能分析工具Profile使用例項,文中通過示例程式碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
程式碼優化的前提是需要了解效能瓶頸在什麼地方,程式執行的主要時間是消耗在哪裡,對於比較複雜的程式碼可以藉助一些工具來定位,python 內建了豐富的效能分析工具,如 profile,cProfile 與 hotshot 等。其中 Profiler 是 python 自帶的一組程式,能夠描述程式執行時候的效能,並提供各種統計幫助使用者定位程式的效能瓶頸。Python 標準模組提供三種 profilers:cProfile,profile 以及 hotshot。
profile 的使用非常簡單,只需要在使用之前進行 import 即可,也可以在命令列中使用。
使用Profile
測試示例:
import profile def a(): sum = 0 for i in range(1,10001): sum += i return sum def b(): sum = 0 for i in range(1,100): sum += a() return sum if __name__ == "__main__": profile.run("b()")
輸出結果:
<br data-filtered="filtered"> 104 function calls in 0.094 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.094 0.094 :0(exec) 1 0.000 0.000 0.000 0.000 :0(setprofile) 1 0.000 0.000 0.094 0.094 <string>:1(<module>) 1 0.000 0.000 0.094 0.094 profile:0(b()) 0 0.000 0.000 profile:0(profiler) 99 0.094 0.001 0.094 0.001 test.py:15(a) 1 0.000 0.000 0.094 0.094 test.py:21(b)
其中輸出每列的具體解釋如下:
●ncalls:表示函式呼叫的次數;
●tottime:表示指定函式的總的執行時間,除掉函式中呼叫子函式的執行時間;
●percall:(第一個 percall)等於 tottime/ncalls;
●cumtime:表示該函式及其所有子函式的呼叫執行的時間,即函式開始呼叫到返回的時間;
●percall:(第二個 percall)即函式執行一次的平均時間,等於 cumtime/ncalls;
●filename:lineno(function):每個函式呼叫的具體資訊;
如果需要將輸出以日誌的形式儲存,只需要在呼叫的時候加入另外一個引數。如 profile.run(“profileTest()”,”testprof”)。
命令列
如果我們不想在程式中呼叫profile庫使用,可以在命令列使用命令。
import os def a(): sum = 0 for i in range(1,100): sum += a() return sum print b()
執行命令檢視效能分析結果
python -m cProfile test.py
將效能分析結果儲存到result檔案
python -m cProfile -o result test.py
使用pstats來格式化顯示結果
python -c "import pstats; p=pstats.Stats('reslut); p.print_stats()" python -c "import pstats; p=pstats.Stats('result'); p.sort_stats('time').print_stats()
sort_stats支援以下引數:
calls,cumulative,file,line,module,name,nfl,pcalls,stdname,time
測試示例:在程式碼中直接使用profile與stats
import os def a(): sum = 0 for i in range(1,10001): sum += i return sum def b(): sum = 0 for i in range(1,100): sum += a() return sum print b() import cProfile# cProfile.run("b()") cProfile.run("b()","result") import pstats pstats.Stats('result').sort_stats(-1).print_stats()
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。