2
2

More than 1 year has passed since last update.

【Python】コードの実行時間を計測するためのストップウォッチを作る

Last updated at Posted at 2021-10-04
class StopWatch:
    """
    実行時間計測クラス
    ブロックを抜けたときに、ブロック全体の実行時間を表示する(例外発生時を除く)

    <使用例>
        with StopWatch('なんかの機能'):
            do_something()
    <表示例>
        なんかの機能
        実行時間: 01:23:45
    """
    # with ブロッックに入った時に呼び出される
    def __enter__(self, title=''):
        # 計測対象の名称
        self._title = title
        # 開始時間
        self._start_time = datetime.now()

    # with ブロッックを抜けた時に呼び出される
    def __exit__(self, exc_type, exc_value, traceback):
        # 例外が発生していないか
        if exc_type is None:
            # 終了時間
            end_time = datetime.now()
            # 処理時間 = 終了時間 - 開始時間(小数点切り捨て)
            exe_time = str(end_time - self._start_time).split('.')[0]
            # 計測対象の名称表示
            print(self._title)
            # 処理時間表示
            print('実行時間: ' + exe_time)

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