Loading video player…

Python Timer Functions (Overview)

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 video course, you’ll start with the timer functions in Python’s time module and then abstract them into a reusable Timer class. You’ll extend that class to track multiple timers, convert it to a data class for convenience, and finally turn it into a context manager so that you can time a block of code with a single with statement.

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

  • time.perf_counter() is the best choice for accurate timing in Python due to its high resolution.
  • process_time() and time() measure different things, so picking the wrong one can skew your results.
  • You can create a custom timer class to encapsulate timing logic and reuse it across multiple parts of your program.
  • Turning your timer into a data class cuts down on boilerplate and makes it easier to configure.
  • 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, data classes, and context managers work in Python.

Download

Course Slides (.pdf)

1.7 MB
Download

Sample Code (.zip)

4.9 KB

Become a Member to join the conversation.