メソッドの実行時間を測定するのに、毎回メソッドの開始と終わりの時刻を計測して
差分を計算するのは手間ではないですか?
なので、デコレーターで実現してみました。
デコレーター
import time
def measure_runtime(method):
def wrapper(*args, **kw):
# 始点タイム
ts = time.time()
# methodの実行
rt = method(*args, **kw)
# 終点タイム
te = time.time()
# 差分の表示
print ('%s %2.2f ms' % (method.__name__, (te - ts) * 1000))
return rt
return wrapper
単純に、メソッドの前後でunix時間を取得して差分を表示させているだけのプログラムになります。
logに吐き出したい場合は、print
をloggerに変更しまししょう。
メソッドに追加
では、実際にメソッドにデコレーターを付けてみましょう。
viewの各メソッドに追加した例です。
@measure_runtime
def index(request):
...
return render(request, 'sample/index.html')
@measure_runtime
def detail(request, question_id):
...
return render(request, 'sample/detail.html')
計測
ビルトインサーバーを立ち上げ、index,detailページにアクセスしてみましょう。
$> python manage.py runserver
...
index 17.64 ms
detail 10.99 ms
各ページに掛かった秒数が表示されました。
一回作ってしまえば、どこにでも付けられるのでお勧めです。