measure function execution time with this simple python decorator

How to measure execution time of a function in Python, with example

this would be the timeit decorator:

from functools import wraps
import time


def timeit(func):
    @wraps(func)
    def timeit_wrapper(*args, **kwargs):
        start_time = time.perf_counter()
        result = func(*args, **kwargs)
        end_time = time.perf_counter()
        total_time = end_time - start_time
        print(f'Function {func.__name__}{args} {kwargs} Took {total_time:.4f} seconds')
        return result
    return timeit_wrapper

example how this decorator works:

@timeit
def lol():
    print("lmao, Serhii is the best")
    return {"status": "KING"}

Printout of the timeit decorator would be:

Function lol() {} Took 0.0000 seconds

 


Comments

Leave a Reply

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