Search code examples
pythonpython-2.7python-3.xpython-internalsgettimeofday

python time.time() differences in python 2 vs 3


I am wondering why python 2.7 uses gettimeofday() when running time.time() but yet in python 3.4 it does not?

It appears when running strace that it may be querying /etc/localtime


Solution

  • Python 3 will use gettimeofday() when your system has been detected to support this at compile time. However, on POSIX systems it'll only use that if clock_gettime(CLOCK_REALTIME) is not available instead; according to the POSIX 2008 standard the latter is preferred as gettimeofday() is considered obsolete.

    At runtime, you can query what Python thought your system could support at compile time by using the time.get_clock_info() function, which returns a namedtuple instance with a implementation field:

    implementation: The name of the underlying C function used to get the clock value

    On my OSX 10.11 system, for the 'time' clock, that produces gettimeofday():

    >>> time.get_clock_info('time').implementation
    'gettimeofday()'
    

    You can read through the pygettimeofday() C implementation to see what implementations may be used; on Windows GetSystemTimeAsFileTime() is used for example.