How to Measure Function Execution Time in Python

import time

def measure_time(func):
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        print(f"Execution time: {end_time - start_time:.4f} seconds")
        return result
    return wrapper

@measure_time
def time_consuming_function():
    # Simulate a time-consuming operation
    time.sleep(2)
    print("Function executed!")

time_consuming_function()

Output:

Function executed!
Execution time: 2.0002 seconds

Leave a Comment

Your email address will not be published.