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.
Python code
24 linesimport 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
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
- Use a function decorator like `@contextlib.contextmanager` to create a timer without a class.
- 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
More from Errors & debugging
- Catch RecursionError and Fail Gracefully in Python easy
- Catch ValueError and print friendly message in Python easy
- Collect Multiple Validation Errors in Python Before Raising medium
- Handle ValueError and ZeroDivisionError in Python with try except easy
- How to Add a Correlation ID to Logging Records in Python medium
- How to Assert Preconditions with Descriptive Messages in Python easy
Keep learning
Related tutorials and quizzes for this topic.