- Dec 2023
-
superfastpython.com superfastpython.com
-
Measure Execution Time With time.monotonic()
The
time.monotonic()
function returns time stamps from a clock that cannot go backwards, as its name suggests.In mathematics, monotonic, e.g. a monotonic function means a function whose output over increases (or decreaes).
This means that the result from the
time.monotonic()
function will never be before the result from a prior call.Return the value (in fractional seconds) of a monotonic clock, i.e. a clock that cannot go backwards.
It is a high-resolution time stamp, although is not relative to epoch-like
time.time()
. Instead, liketime.perf_counter()
uses a separate timer separate from the system clock.The
time.monotonic()
has a lower resolution than thetime.perf_counter()
function.This means that values from the
time.monotonic()
function can be compared to each other, relatively, but not to the system clock.Like the
time.perf_counter()
function,time.monotonic()
function is “system-wide”, meaning that it is not affected by changes to the system clock, such as updates or clock adjustments due to time synchronization.Like the
time.perf_counter()
function, thetime.monotonic()
function was introduced in Python version 3.3 with the intent of addressing the limitations of thetime.time()
function tied to the system clock, such as use in short-duration benchmarking.Monotonic clock (cannot go backward), not affected by system clock updates.
-