目次
プロファイリングツールを使った性能解析ができます
工作HardwareHubからのお知らせ
プログラムのある箇所が実行された時間や回数を計測するためのプロファイラについて、Python には標準で cProfile と profile があります。どちらも同じインタフェースを提供しており、通常は C の拡張でありオーバーヘッドの小さい cProfile を利用します。profile はプロファイラを拡張したいときに利用する C に依存していない実装です。
cProfile
結果の読み方
#!/usr/bin/python
# -*- coding: utf-8 -*-
from cProfile import Profile
from time import sleep
def Main():
pr = Profile()
pr.runcall(sleep, 1)
pr.print_stats()
if __name__ == '__main__':
Main()
実行例
$ python sample.py
2 function calls in 1.004 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
1 1.004 1.004 1.004 1.004 {time.sleep}
- 関数が実行された回数は 2 回で 1.004 秒を要した
- 関数名の順に表示
ncalls
各関数の実行回数tottime
各関数の実行に要した時間 (内部でサブ関数の実行に要した時間を除く)percall
tottime / ncallscumtime
各関数の実行に要した時間 (内部でサブ関数の実行に要した時間を含む)percall
cumtime / ncalls
結果のファイルへの書き出しおよび利用
書き出し
#!/usr/bin/python
# -*- coding: utf-8 -*-
from cProfile import Profile
from time import sleep
def Main():
pr = Profile()
pr.runcall(sleep, 1)
pr.dump_stats('sample.profile')
if __name__ == '__main__':
Main()
読み込み
#!/usr/bin/python
# -*- coding: utf-8 -*-
from pstats import Stats
def Main():
stats = Stats('./sample.profile')
stats.sort_stats('cumtime') # 指定した情報でソートできます。
stats.print_stats(10) # トップ10
print stats.total_tt # tottime の合計
if __name__ == '__main__':
Main()
RunSnakeRun
cProfile の出力結果を可視化するためのツールとしては RunSnakeRun が利用できます。
インストール
sudo apt install runsnakerun
可視化
runsnake sample.profile
今回は time.sleep がすべての実行時間を占めていますが、より複雑な状況では可視化できると便利です。
0
記事の執筆者にステッカーを贈る
有益な情報に対するお礼として、またはコメント欄における質問への返答に対するお礼として、 記事の読者は、執筆者に有料のステッカーを贈ることができます。
さらに詳しく →Feedbacks
ログインするとコメントを投稿できます。
関連記事
- Python コードスニペット (条件分岐)if-elif-else sample.py #!/usr/bin/python # -*- coding: utf-8 -*- # コメント内であっても、ASCII外の文字が含まれる場合はエンコーディング情報が必須 x = 1 # 一行スタイル if x==0: print 'a' # 参考: and,or,notが使用可能 (&&,||はエラー) elif x==1: p...
- Python コードスニペット (リスト、タプル、ディクショナリ)リスト range 「0から10まで」といった範囲をリスト形式で生成します。 sample.py print range(10) # for(int i=0; i<10; ++i) ← C言語などのfor文と比較 print range(5,10) # for(int i=5; i<10; ++i) print range(5,10,2) # for(int i=5; i<10;...
- ZeroMQ (zmq) の Python サンプルコードZeroMQ を Python から利用する場合のサンプルコードを記載します。 Fixing the World To fix the world, we needed to do two things. One, to solve the general problem of "how to connect any code to any code, anywhere". Two, to wra...
- Matplotlib/SciPy/pandas/NumPy サンプルコードPython で数学的なことを試すときに利用される Matplotlib/SciPy/pandas/NumPy についてサンプルコードを記載します。 Matplotlib SciPy pandas [NumPy](https://www.numpy
- pytest の基本的な使い方pytest の基本的な使い方を記載します。 適宜参照するための公式ドキュメントページ Full pytest documentation API Reference インストール 適当なパッケージ