How to Start and Stop Time Measurements with Python#
Instead of using Timer for Python, you can also make your own performance timer.
Adding a Stop Watch to Your Code#
Python has different methods to measurement time as a stop watch. The most common is the time
standard library, and this will be sufficient for most use cases.
But if you want higher precision, you can use the out-of-the box methods perf_counter
or perf_counter_ns
. Both part of the time
standard library, so you don't need to install anything beyond a Python interpreter.
Overview of Different Methods#
Here's a comparison of different time measurement methods from the standard librray:
Method | Description | Returns |
---|---|---|
time() | Basic time measurement with system clock resolution. Suitable for general timing needs. Less precise as it can be affected by system clock updates. | float seconds |
perf_counter() | High-resolution performance counter for benchmarking. Most suitable for measuring elapsed time. Returns floating-point seconds. Not affected by system clock updates. | float seconds |
perf_counter_ns() | Similar to perf_counter() , but returns nanoseconds as integer. Highest precision timing available in Python. Best for very precise measurements. | int nanoseconds |
Basic Examples#
Each method follows the same pattern:
- Start the timer
- Execute the code
- Stop the timer
- Calculate the elapsed time
The main differences are in the precision and units of the returned values. Please try the following different methods to start and stop time to see what works best for you:
Using time()
#
Python | |
---|---|
1 2 3 4 5 6 7 8 9 10 |
|
Using perf_counter()
#
Python | |
---|---|
1 2 3 4 5 6 7 8 9 10 |
|
Using perf_counter_ns()
#
Python | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
Using Timer for Python#
Alternatively, you can achieve the same result with Timer for Python using less code. Simply wrap the Timer around the code you want to measure. This can be done with or without the with
statement for context management:
Python | |
---|---|
1 2 3 4 |
|
Or use the @function_timer()
as function decorator to measure the performance of a function:
Python | |
---|---|
1 2 3 4 5 6 7 |
|
Advanced Examples#
Calculate the Average of Multiple Runs#
Imagine you want to measure the performance of a function. Since each run may vary from run to run, let's calculate the average execution time of the function across multiple runs.
Here's a simple example:
Python | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|