How to Build a Simple Debug Timer in Python

Create a context manager class to time the execution of a code block with a one-line printout.

Easy Python 3.9+ Aug 9, 2026 Errors & debugging 16 views 0 copies

Python code

24 lines
Python 3.9+
import time


class DebugTimer:
    """Context manager that times the execution of a code block."""

    def __init__(self, label="Operation"):
        self.label = label
        self.start_time = None

    def __enter__(self):
        self.start_time = time.perf_counter()
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        elapsed = time.perf_counter() - self.start_time
        print(f"{self.label}: {elapsed:.6f} seconds")
        return False


if __name__ == "__main__":
    with DebugTimer("List comprehension"):
        result = [x * x for x in range(1000)]
    print(f"Result length: {len(result)}")

Output

stdout
List comprehension: 0.000456 seconds
Result length: 1000

How it works

The DebugTimer class implements the context manager protocol by defining __enter__ and __exit__. time.perf_counter() provides a high-resolution timer that avoids the inaccuracies of time.time(). The __enter__ method records the start time and returns the instance, allowing optional access to the timer object. __exit__ computes the elapsed time and prints it with six decimals, ensuring consistent formatting. Returning False from __exit__ propagates any exceptions that occur inside the with block.

Common mistakes

  • Using `time.time()` instead of `time.perf_counter()` for timers, which can be less precise.
  • Returning `True` from `__exit__`, which suppresses exceptions and hides debugging information.
  • Forgetting to call the timer, so the context manager is never entered.
  • Not using a label, making output less readable when timing multiple blocks.

Variations

  1. Use a function decorator like `@contextlib.contextmanager` to create a timer without a class.
  2. Store the elapsed time in an attribute for programmatic access after the block.

Real-world use cases

  • Measure database query performance in a development environment to spot slow endpoints.
  • Time expensive computation blocks during code profiling to identify bottlenecks.
  • Log execution time of critical sections in a service for monitoring and alerting.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Errors & debugging

Related tutorials and quizzes for this topic.