Skip to content

Measure the execution time of a function in Python using decorators

We can use decorators to calculate the execution time of a function.

Advertisements
from time import time


def performance(fn):
    def wrapper(*args, **kwargs):
        t1 = time()
        result = fn(*args, **kwargs)
        t2 = time()
        print(t2-t1)
        return result

    return wrapper


@performance
def sample_fn():
    for i in range(10000):
        i * 5


sample_fn()

//0.00142478942871

Here the output is in milliseconds.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.