背景
- pythonでDB query実行時間などを残りたい
- いつでもend - startで時間を計算することが面倒
普通のやり方
time_sta = time.perf_counter()
time.sleep(2)
time_end = time.perf_counter()
print(time_end - time_sta)
対策
- rubyのブロックように実装して便利になると思う
- pythonではrubyのblockのような予約語がない
実装してみる
from contextlib import contextmanager
import time
import sys
@contextmanager
def time_count(function_name: str):
time_sta = time.perf_counter()
yield
time_end = time.perf_counter()
print(f"{function_name}の実行時間: {time_end - time_sta}")
def get_tenant_info():
with time_count2(sys._getframe().f_code.co_name):
time.sleep(2)
get_tenant_info() # -> get_tenant_infoの実行時間: 2.0020375240128487
メリット
- ブロックで実行時間をログに残って、実装方法を固定できる
- ソードコードの量が少なくなって、バグもない