Course contentsShow
← Python
Lesson 625 of 1,06010. Advanced Language FeaturesFree lesson

Measuring Execution Time With Custom Context Managers

Learners will build a utility context manager that captures and logs the execution duration of code blocks to profile application performance bottlenecks.

In this lesson, you will learn how to build a custom context manager that automatically logs the execution duration of any code block to identify performance bottlenecks in your application.

The Concept

While decorators are excellent for timing entire functions, context managers allow you to surgically profile specific segments of code—like a slow database query or a complex loop—without modifying the rest of the function. By utilizing the __enter__ and __exit__ dunder methods, we can capture the start time right before a code block runs and calculate the elapsed time immediately after it finishes.

Building the Profiler

We define a class that stores the start time when entering the with block and calculates the difference when exiting.

import time

class Timer:
    def __enter__(self):
        self.start = time.perf_counter()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.end = time.perf_counter()
        self.duration = self.end - self.start
        print(f"Code block executed in {self.duration:.4f} seconds")

# Usage
with Timer():
    # Simulate a heavy operation
    total = sum(range(10_000_000))

Why Use a Context Manager?

This approach offers two major advantages:

  1. Precision: You can wrap only the logic you suspect is slow rather than profiling the entire function overhead.
  2. Readability: The with statement explicitly marks the start and end of the region under investigation. If the code inside the block raises an exception, the __exit__ method still executes, ensuring you receive a report on how long the code ran before failing.

For more advanced needs, you can easily extend the __exit__ method to log these durations to a file or an external monitoring service, effectively turning this simple utility into a powerful production profiling tool.

Key Takeaway: By implementing __enter__ and __exit__, you can create a reusable Timer context manager that provides high-precision performance monitoring for specific code segments with minimal boilerplate.