- Dec 2023
-
superfastpython.com superfastpython.com
-
Measure Execution Time With time.perf_counter()
The time.perf_counter() function reports the value of a performance counter on the system.
It does not report the time since epoch like time.time().
Return the value (in fractional seconds) of a performance counter, i.e. a clock with the highest available resolution to measure a short duration. It does include time elapsed during sleep and is system-wide.
The returned value in seconds with fractional components (e.g. milliseconds and nanoseconds), provides a high-resolution timestamp.
Calculating the difference between two timestamps from the time.perf_counter() allows high-resolution execution time benchmarking, e.g. in the millisecond and nanosecond range.
The timestamp from the
time.perf_counter()
function is consistent, meaning that two durations can be compared relative to each other in a meaningful way.The
time.perf_counter()
function was introduced in Python version 3.3 with the intended use for short-duration benchmarking.The
perf_counter()
function was specifically designed to overcome the limitations of other time functions to ensure that the result is consistent across platforms and monotonic (always increasing).For accuracy, the
timeit
module uses thetime.perf_counter()
internally.
-