Search code examples
pythontime

High-precision clock in Python


Is there a way to measure time with high-precision in Python --- more precise than one second? I doubt that there is a cross-platform way of doing that; I'm interesting in high precision time on Unix, particularly Solaris running on a Sun SPARC machine.

timeit seems to be capable of high-precision time measurement, but rather than measure how long a code snippet takes, I'd like to directly access the time values.


Solution

  • The standard time.time() function provides sub-second precision, though that precision varies by platform. For Linux and Mac precision is +- 1 microsecond or 0.001 milliseconds. Python on Windows with Python < 3.7 uses +- 16 milliseconds precision due to clock implementation problems due to process interrupts. The timeit module can provide higher resolution if you're measuring execution time.

    >>> import time
    >>> time.time()        #return seconds from epoch
    1261367718.971009      
    

    Python 3.7 introduces new functions to the time module that provide higher resolution for longer time periods:

    >>> import time
    >>> time.time_ns()
    1530228533161016309
    >>> time.time_ns() / (10 ** 9) # convert to floating-point seconds
    1530228544.0792289