7
6

More than 5 years have passed since last update.

Pythonで部分的なコードの実行時間を測る

Last updated at Posted at 2019-02-26

Pythonで部分的なコードの実行時間を知りたい時のtipsです。
すぐに忘れるので、メモを兼ねて共有します。

実装

まず、contextmanagerでデコレーターを作っておきます。

from contextlib import contextmanager
import time

@contextmanager
def timer(title):
    start = time.time()
    yield
    print("{} - done in {:.3f}s".format(title, time.time() - start))

使い方

with timer('hello world'):
    # 処理

関数内に関数を定義して、ラッパーを用いることでも実装できるのですが、
contextlibのcontextmanagerを使うことでより簡潔になります。

デコレータ内の「yield」でwithステートメント内の処理が実行されて、時間を計測できるようになっています。
部分的なコードの実行時間を測りたい時に便利なので、使ってみてください。

7
6
1

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
7
6