How to get the time in ms between two calls in Python

Question:

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 deprecated
  • time.time() is based on the system’s clock to determine seconds since epoch and has unreliable leap second handling
  • time.process_time() and time.thread_time() can’t be used because they ignore time spent sleeping
  • time.monotonic() only ticks 64 times per second
  • time.perf_counter() has lossy nano precision encoded as float
  • time.perf_counter_ns() has precise nano resolution but encoded as int, so can’t track more than 4 seconds

Of 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?)

Answers:

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
Answered By: chepner
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.