I would use Rad's answer with the decorator, and the main thing I would change is to make sure to use a monotonic clock, so instead of t.time()
use t.monotonic()
, or for greater precision t.monotonic_ns()
. But this requires that you use python v3.3 or higher, otherwise you may try this ctypes variant of getting a monotonic clock.
Here's from python3 docs:
time.monotonic() → float
Return the value (in fractional seconds) of a monotonic clock, i.e. a clock that cannot go backwards. The clock is not affected by system clock updates. The reference point of the returned value is undefined, so that only the difference between the results of two calls is valid.
Use monotonic_ns() to avoid the precision loss caused by the float type.
New in version 3.3.
Changed in version 3.5: The function is now always available and always system-wide.
Changed in version 3.10: On macOS, the function is now system-wide.
time.monotonic_ns() → int
Similar to monotonic(), but return time as nanoseconds.
New in version 3.7.
>>> import time as t
>>> t.time()
1666507313.6913335
>>> t.monotonic_ns()
2346741390948
>>> t.monotonic_ns()
2350236290783
>>> t.monotonic()
2353.851540444
>>> t.monotonic_ns()
2356366587038
>>> t.get_clock_info('time')
namespace(implementation='clock_gettime(CLOCK_REALTIME)', monotonic=False, adjustable=True, resolution=1e-09)
>>> t.get_clock_info('monotonic')
namespace(implementation='clock_gettime(CLOCK_MONOTONIC)', monotonic=True, adjustable=False, resolution=1e-09)
>>>
>>> t.monotonic()
3475.071162687
>>> t.monotonic_ns()/10**9
3475.877335106
Read more info here and here.