LoginSignup
0
0

More than 1 year has passed since last update.

【Django】DjangoでLine Profilerを使う

Last updated at Posted at 2022-04-08

Line Profilerとは

プログラムを行単位でプロファイリングできるモジュールです。今回はDjangoアプリ内で行ごとの処理時間を計測し、コンソールに表示させてみます。

Line Profilerの使い方

1. Line Profilerをインストール

$ pip install line_profiler

インストール後は $ pip freeze > requirements.txt しておくと良いでしょう。

2. 処理時間を計測したいファイル(views.pyなど)に下記を追加

views.py
# Line Profiler
import line_profiler
import atexit

profile = line_profiler.LineProfiler()
atexit.register(profile.print_stats)

# 測定したい関数にアノテーションを付ける
@profile
def foo():
    ...

3. runserverする

$ python manage.py runserver

4. ブラウザを更新するなりして関数を実行する

5. Ctrl+c でrunserverを終了する。

計測結果がコンソールに表示されます↓

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
     3                                           @profile
     4                                           def foo():
     5         1    1557939.0      0.3     50.9      print('Hello World')
     6         1   10541423.0      2.1     49.1      print('foo')
0
0
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
0
0