LoginSignup
3
2

More than 5 years have passed since last update.

デコレーターを使って関数の実行時間を計測・表示する

Posted at

Python3を使っています。

実装

from datetime import datetime
from time import sleep

def print_process_time(func):
    """ 関数の実行時間を表示する
    """
    def wrapped(*args, **kwargs):
        start = datetime.now()
        result = func(*args, **kwargs)
        process_time_sec = (datetime.now() - start).total_seconds()
        print("Process time: %f sec" % process_time_sec)
        return result
    return wrapped


@print_process_time
def foo_method():
    """ 計測対象の関数
    """
    print("foo_method start")
    sleep(1.5)
    print("foo_method end")


if __name__ == "__main__":
    foo_method()

実行

% python3 foo.py
foo_method start
foo_method end
Process time: 1.500384 sec
3
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
3
2