1. 程式人生 > 實用技巧 >cProfile分析程式效能

cProfile分析程式效能

Python標準庫中提供了三種用來分析程式效能的模組,分別是cProfile, profile和hotshot,另外還有一個輔助模組stats。這些模組提供了對Python程式的確定性分析功能,同時也提供了相應的報表生成工具,方便使用者快速地檢查和分析結果。

這三個效能分析模組的介紹如下:

cProfile:基於lsprof的用C語言實現的擴充套件應用,執行開銷比較合理,適合分析執行時間較長的程式,推薦使用這個模組;

profile:純Python實現的效能分析模組,介面和cProfile一致。但在分析程式時增加了很大的執行開銷。不過,如果你想擴充套件profiler的功能,可以通過繼承這個模組實現;


hotshot:一個試驗性的C模組,減少了效能分析時的執行開銷,但是需要更長的資料後處理的次數。目前這個模組不再被維護,有可能在新版本中被棄用。

2種方式使用:

cProfile.run('func(arg)','filename.txt')     # 調優函式,在指令碼中使用
python -m cProfile myscript.py [-o filename.txt]    # 調優指令碼,在命令列使用   -o表示輸出到檔案

輸出解釋

         7 function calls in 0.088 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        
1 0.003 0.003 0.088 0.088 <string>:1(<module>) 1 0.000 0.000 0.085 0.085 cProfile模組.py:14(f3) 1 0.010 0.010 0.010 0.010 cProfile模組.py:15(<listcomp>) 1 0.015 0.015 0.015 0.015 cProfile模組.py:17(<listcomp>) 1 0.000 0.000 0.088 0.088 {built-in
method builtins.exec} 1 0.060 0.060 0.060 0.060 {built-in method builtins.sorted} 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}

共有 7次函式呼叫,耗時0.088秒,原始呼叫為 0次,原始呼叫代表不包含遞迴呼叫。

ncalls 函式的被呼叫次數

tottime 函式總計執行時間,除去函式中呼叫的函式執行時間

percall 函式執行一次的平均時間,等於tottime/ncalls

cumtime 函式總計執行時間,含呼叫的函式執行時間

percall 函式執行一次的平均時間,等於cumtime/ncalls

filename:lineno(function) 函式所在的檔名,函式的行號,函式名