LoginSignup
6
5

More than 1 year has passed since last update.

pythonでブロックで実行時間をログに残る

Posted at

背景

  • 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     

メリット

  • ブロックで実行時間をログに残って、実装方法を固定できる
  • ソードコードの量が少なくなって、バグもない
6
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
6
5