Course contentsShow
← Python
Lesson 900 of 1,06014. Concurrency and PerformanceFree lesson

Measuring Execution Time with Decorators

Create reusable timing decorators to accurately capture the execution duration of specific functions and identify potential performance bottlenecks in your code.

In this lesson, you will learn how to create reusable timing decorators to quantify the performance of your functions and pinpoint bottlenecks.

When building high-concurrency systems, intuition about performance is rarely enough. To optimize your code, you need empirical data. Using a decorator to wrap your functions allows you to inject timing logic—capturing the start and end time—without cluttering your core business logic.

Creating the Timing Decorator

To measure execution time, we use the time module. By defining a decorator, we can apply this logic to any function consistently.

import time
import functools

def measure_time(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start_time = time.perf_counter()
        result = func(*args, **kwargs)
        end_time = time.perf_counter()
        duration = end_time - start_time
        print(f"Function '{func.__name__}' took {duration:.4f} seconds.")
        return result
    return wrapper

Why use perf_counter()?

When measuring performance, avoid time.time(). It represents "wall-clock" time and is susceptible to system clock updates. Instead, time.perf_counter() provides a high-resolution clock specifically designed for measuring short durations, making it the standard for profiling performance bottlenecks.

Applying the Decorator

Simply annotate the functions you suspect are slowing down your execution pipeline:

@measure_time
def process_data_heavy(data):
    # Simulate a time-consuming task
    time.sleep(1.2)
    return len(data)

# Calling the function now automatically reports its execution time
process_data_heavy([1, 2, 3]) 
# Output: Function 'process_data_heavy' took 1.2005 seconds.

By decoupling the timing logic from your algorithms, you maintain clean code while gaining the ability to audit any portion of your application. This is particularly useful when testing whether refactoring a function to use a ProcessPoolExecutor or an async task actually yields the performance gains you expect.

Key Takeaway: Use a reusable decorator with time.perf_counter() to transparently capture execution duration and gain empirical evidence for your performance optimization efforts.