How does one properly get the number of millis between two successive calls? There's a bunch of different ways to get or profile time, and all of them seem to have problems:
time.clock()
is deprecatedtime.time()
is based on the system's clock to determine seconds since epoch and has unreliable leap second handlingtime.process_time()
and time.thread_time()
can't be used because they ignore time spent sleepingtime.monotonic()
only ticks 64 times per secondtime.perf_counter()
has lossy nano precision encoded as floattime.perf_counter_ns()
has precise nano resolution but encoded as int, so can't track more than 4 secondsOf these, time.perf_counter()
is the only option for millisecond precision (i.e. most use cases) but is there something better? (e.g. some kind of perf_counter_ms
that yields an int
but with a reliability interval of four million seconds instead of 4 seconds?)
time.perf_counter_ns()
has precise nano resolution but encoded as int, so can't track more than 4 seconds
This is incorrect. perf_counter_ns
returns an arbitrary-precision Python int
, not a 32-bit integer. As a result, it's not limited to returning a value of 2**32 nanoseconds or less. You can divide the difference between two return values by 1,000,000 to get the number of milliseconds.
>>> from time import sleep, perf_counter_ns as pcns
>>> t1 = pcns(); sleep(5); (pcns() - t1) / 1_000_000
5000.45865