Python Timer Functions: Three Ways to Monitor Your Code

Python Timer Functions: Three Ways to Monitor Your Code

by Geir Arne Hjelle Reading time estimate 1h 5m intermediate python stdlib

A timer is a powerful tool for monitoring the performance of your Python code. By using the time.perf_counter() function, you can measure execution time with exceptional precision, making it ideal for benchmarking. Using a timer involves recording timestamps before and after a specific code block and calculating the time difference to determine how long your code took to run.

In this tutorial, you’ll explore three different approaches to implementing timers: classes, decorators, and context managers. Each method offers unique advantages, and you’ll learn when and how to use them to achieve optimal results. Plus, you’ll have a fully functional Python timer that can be applied to any program to measure execution time efficiently.

By the end of this tutorial, you’ll understand that:

  • time.perf_counter() is the best choice for accurate timing in Python due to its high resolution.
  • You can create custom timer classes to encapsulate timing logic and reuse it across multiple parts of your program.
  • Using decorators lets you seamlessly add timing functionality to existing functions without altering their code.
  • You can leverage context managers to neatly measure execution time in specific code blocks, improving both resource management and code clarity.

Along the way, you’ll gain deeper insights into how classes, decorators, and context managers work in Python. As you explore real-world examples, you’ll discover how these concepts can not only help you measure code performance but also enhance your overall Python programming skills.

Python Timers

First, you’ll take a look at some example code that you’ll use throughout the tutorial. Later, you’ll add a Python timer to this code to monitor its performance. You’ll also learn some of the simplest ways to measure the running time of this example.

Python Timer Functions

If you check out the built-in time module in Python, then you’ll notice several functions that can measure time:

Python 3.7 introduced several new functions, like thread_time(), as well as nanosecond versions of all the functions above, named with an _ns suffix. For example, perf_counter_ns() is the nanosecond version of perf_counter(). You’ll learn more about these functions later. For now, note what the documentation has to say about perf_counter():