3
5

More than 3 years have passed since last update.

デコレーターによるメソッド実行時間計測 in Django

Last updated at Posted at 2020-11-28

メソッドの実行時間を測定するのに、毎回メソッドの開始と終わりの時刻を計測して
差分を計算するのは手間ではないですか?

なので、デコレーターで実現してみました。

デコレーター

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

各ページに掛かった秒数が表示されました。
一回作ってしまえば、どこにでも付けられるのでお勧めです。

3
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5