LoginSignup
1
2

More than 3 years have passed since last update.

Pythonで関数の実行時間を測定する

Last updated at Posted at 2021-03-31

デコレータを使って関数の実行時間を測定する方法です。このデコレータをコピペすれば、好きな関数の実行時間を手軽に測ることができるようになります。

まず以下のデコレータをコピペします。

import time

def exec_time(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        res = func(*args, **kwargs)
        end = time.time()
        print(
            "execution time of {func_name} (sec): {second}"
            .format(second=end-start, func_name=func.__name__))
        return res
    return wrapper

関数にデコレータをつけて実行します。手軽につけたり外したりできるのがデコレータの魅力ですね。


@exec_time
def functionA():
    for i in range(100 * 100):
        a = 1 + 1

@exec_time
def functionB():
    for i in range(100 * 100 * 100):
        a = 1 + 1

functionA()
functionB()

実行結果は以下のようになります。

execution time of functionA (sec): 0.003993988037109375
execution time of functionB (sec): 0.23200011253356934

お役に立てば幸いです。

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