Creating a Decorator that Times a Function

88 views

Creating a Decorator that Times a Function

Creating a Decorator that Times a Function

How can I create a decorator to measure function execution time?

solveurit24@gmail.com Changed status to publish February 20, 2025
0

Use the time module:

import time

def timing_decorator(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(f"{func.__name__} took {end - start} seconds.")
        return result
    return wrapper

@timing_decorator
def some_function():
    time.sleep(2)

solveurit24@gmail.com Changed status to publish February 20, 2025
0