LoginSignup
1
1

More than 3 years have passed since last update.

PythonのWithで実行時間計測

Posted at

出来るようになること

withを使用して時間計測ができるようになる。
Kaggleなどで時間を計測するときに使える。

参考

メルカリコンペ1位のコードで使用されていました。

使用方法

コンテキストマネージャとして使用したい関数の定義の直前に@contextmanagerと記載するだけ。

timerが呼ばれた時に初期時間がt0に格納されて、yeildで一時関数から抜ける。
time.sleep(1)の処理終了後に再びtimerに戻ってきて初期時間との差分を出力している。

qiita.rb
from contextlib import contextmanager
import time

@contextmanager
def timer(name):
    t0 = time.time()
    print("start")
    yield
    print("end")
    print(f'[{name}] done in {time.time() - t0:.0f} s')


with timer('process train'): 
        time.sleep(1)

image.png

@contextmanagerの記載がない場合はtimerはcontextmanagerとして動作できないためエラーになる。
image.png

コンテキストマネージャー

with分とコンテキストマネージャー
コンテキストマネージャは、コードブロックを実行するために必要な入り口および出口の処理を扱う。

以下の例のように、コンテキストマネージャクラスには開始用の処理と終了時用の処理が記載されている。そのため、@contextmanagerでコンテキストマネージャーにすると、開始時と終了時にtimerが呼ばれることになる。@contextmanagerを記載しなかった場合はenterの定義がないためエラーとなった。
image.png
参考

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