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.
Decorators Q&A Transcript: Click here to get access to a 25-page chat log from our Python decorators Q&A session in the Real Python Community Slack where we discussed common decorator questions.
Take the Quiz: Test your knowledge with our interactive “Python Timer Functions: Three Ways to Monitor Your Code” quiz. You’ll receive a score upon completion to help you track your learning progress:
Interactive Quiz
Python Timer Functions: Three Ways to Monitor Your CodeTest your knowledge of Python timer functions, from time.perf_counter() to timers built with classes, context managers, and decorators.
Get Your Code: Click here to download the free sample code you’ll use to build a Python timer as a class, context manager, and decorator.
Intermediate Python Deep Dive Live Course: Want more practice with the classes, context managers, and decorators you use to build these timers? Real Python’s Intermediate Python Deep Dive live course covers object-oriented foundations, special methods, scoping, and decorators with an instructor and a small cohort. Join the waitlist to hear about the next dates.
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():
Return the value (in fractional seconds) of a performance counter, i.e. a clock with the highest available resolution to measure a short duration. (Source)
First, you’ll use perf_counter() to create a Python timer. Later, you’ll compare this with other Python timer functions and learn why perf_counter() is usually the best choice.
Example: Download Tutorials
To better compare the different ways that you can add a Python timer to your code, you’ll apply different Python timer functions to the same code example throughout this tutorial. If you already have code that you’d like to measure, then feel free to follow the examples with that instead.
The example that you’ll use in this tutorial is a short function that uses the realpython-reader package to download the latest tutorials available here on Real Python. To learn more about the Real Python Reader and how it works, check out How to Publish an Open-Source Python Package to PyPI. You can install realpython-reader on your system with pip:
$ python -m pip install realpython-reader==1.1.4 Then, you can import the package as reader.
You’ll store the example in a file named latest_tutorial.py. The code consists of one function that downloads and prints the latest tutorial from Real Python:
latest_tutorial.py 1from reader import feed 2 3def main(): 4 """Download and print the latest tutorial from Real Python""" 5 tutorial = feed.get_article(0) 6 print(tutorial) 7 8if __name__ == "__main__": 9 main() realpython-reader handles most of the hard work:
Read the full article at https://realpython.com/python-timer/ »
[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]



