monotonic.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. # -*- coding: utf-8 -*-
  2. """
  3. monotonic
  4. ~~~~~~~~~
  5. This module provides a ``monotonic()`` function which returns the
  6. value (in fractional seconds) of a clock which never goes backwards.
  7. On Python 3.3 or newer, ``monotonic`` will be an alias of
  8. ``time.monotonic`` from the standard library. On older versions,
  9. it will fall back to an equivalent implementation:
  10. +-------------+----------------------------------------+
  11. | Linux, BSD | ``clock_gettime(3)`` |
  12. +-------------+----------------------------------------+
  13. | Windows | ``GetTickCount`` or ``GetTickCount64`` |
  14. +-------------+----------------------------------------+
  15. | OS X | ``mach_absolute_time`` |
  16. +-------------+----------------------------------------+
  17. If no suitable implementation exists for the current platform,
  18. attempting to import this module (or to import from it) will
  19. cause a ``RuntimeError`` exception to be raised.
  20. Copyright 2014, 2015, 2016 Ori Livneh <ori@wikimedia.org>
  21. Licensed under the Apache License, Version 2.0 (the "License");
  22. you may not use this file except in compliance with the License.
  23. You may obtain a copy of the License at
  24. http://www.apache.org/licenses/LICENSE-2.0
  25. Unless required by applicable law or agreed to in writing, software
  26. distributed under the License is distributed on an "AS IS" BASIS,
  27. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  28. See the License for the specific language governing permissions and
  29. limitations under the License.
  30. """
  31. import time
  32. __all__ = ('monotonic',)
  33. try:
  34. monotonic = time.monotonic
  35. except AttributeError:
  36. import ctypes
  37. import ctypes.util
  38. import os
  39. import sys
  40. import threading
  41. try:
  42. if sys.platform == 'darwin': # OS X, iOS
  43. # See Technical Q&A QA1398 of the Mac Developer Library:
  44. # <https://developer.apple.com/library/mac/qa/qa1398/>
  45. libc = ctypes.CDLL('/usr/lib/libc.dylib', use_errno=True)
  46. class mach_timebase_info_data_t(ctypes.Structure):
  47. """System timebase info. Defined in <mach/mach_time.h>."""
  48. _fields_ = (('numer', ctypes.c_uint32),
  49. ('denom', ctypes.c_uint32))
  50. mach_absolute_time = libc.mach_absolute_time
  51. mach_absolute_time.restype = ctypes.c_uint64
  52. timebase = mach_timebase_info_data_t()
  53. libc.mach_timebase_info(ctypes.byref(timebase))
  54. nanoseconds_in_second = 1.0e9
  55. def monotonic():
  56. """Monotonic clock, cannot go backward."""
  57. nanoseconds = mach_absolute_time() * timebase.numer / timebase.denom
  58. return nanoseconds / nanoseconds_in_second
  59. elif sys.platform.startswith('win32') or sys.platform.startswith('cygwin'):
  60. if sys.platform.startswith('cygwin'):
  61. # Note: cygwin implements clock_gettime (CLOCK_MONOTONIC = 4) since
  62. # version 1.7.6. Using raw WinAPI for maximum version compatibility.
  63. # Ugly hack using the wrong calling convention (in 32-bit mode)
  64. # because ctypes has no windll under cygwin (and it also seems that
  65. # the code letting you select stdcall in _ctypes doesn't exist under
  66. # the preprocessor definitions relevant to cygwin).
  67. # This is 'safe' because:
  68. # 1. The ABI of GetTickCount and GetTickCount64 is identical for
  69. # both calling conventions because they both have no parameters.
  70. # 2. libffi masks the problem because after making the call it doesn't
  71. # touch anything through esp and epilogue code restores a correct
  72. # esp from ebp afterwards.
  73. try:
  74. kernel32 = ctypes.cdll.kernel32
  75. except OSError: # 'No such file or directory'
  76. kernel32 = ctypes.cdll.LoadLibrary('kernel32.dll')
  77. else:
  78. kernel32 = ctypes.windll.kernel32
  79. GetTickCount64 = getattr(kernel32, 'GetTickCount64', None)
  80. if GetTickCount64:
  81. # Windows Vista / Windows Server 2008 or newer.
  82. GetTickCount64.restype = ctypes.c_ulonglong
  83. def monotonic():
  84. """Monotonic clock, cannot go backward."""
  85. return GetTickCount64() / 1000.0
  86. else:
  87. # Before Windows Vista.
  88. GetTickCount = kernel32.GetTickCount
  89. GetTickCount.restype = ctypes.c_uint32
  90. get_tick_count_lock = threading.Lock()
  91. get_tick_count_last_sample = 0
  92. get_tick_count_wraparounds = 0
  93. def monotonic():
  94. """Monotonic clock, cannot go backward."""
  95. global get_tick_count_last_sample
  96. global get_tick_count_wraparounds
  97. with get_tick_count_lock:
  98. current_sample = GetTickCount()
  99. if current_sample < get_tick_count_last_sample:
  100. get_tick_count_wraparounds += 1
  101. get_tick_count_last_sample = current_sample
  102. final_milliseconds = get_tick_count_wraparounds << 32
  103. final_milliseconds += get_tick_count_last_sample
  104. return final_milliseconds / 1000.0
  105. else:
  106. try:
  107. clock_gettime = ctypes.CDLL(ctypes.util.find_library('c'),
  108. use_errno=True).clock_gettime
  109. except Exception:
  110. clock_gettime = ctypes.CDLL(ctypes.util.find_library('rt'),
  111. use_errno=True).clock_gettime
  112. class timespec(ctypes.Structure):
  113. """Time specification, as described in clock_gettime(3)."""
  114. _fields_ = (('tv_sec', ctypes.c_long),
  115. ('tv_nsec', ctypes.c_long))
  116. if sys.platform.startswith('linux'):
  117. CLOCK_MONOTONIC = 1
  118. elif sys.platform.startswith('freebsd'):
  119. CLOCK_MONOTONIC = 4
  120. elif sys.platform.startswith('sunos5'):
  121. CLOCK_MONOTONIC = 4
  122. elif 'bsd' in sys.platform:
  123. CLOCK_MONOTONIC = 3
  124. elif sys.platform.startswith('aix'):
  125. CLOCK_MONOTONIC = ctypes.c_longlong(10)
  126. def monotonic():
  127. """Monotonic clock, cannot go backward."""
  128. ts = timespec()
  129. if clock_gettime(CLOCK_MONOTONIC, ctypes.pointer(ts)):
  130. errno = ctypes.get_errno()
  131. raise OSError(errno, os.strerror(errno))
  132. return ts.tv_sec + ts.tv_nsec / 1.0e9
  133. # Perform a sanity-check.
  134. if monotonic() - monotonic() > 0:
  135. raise ValueError('monotonic() is not monotonic!')
  136. except Exception as e:
  137. raise RuntimeError('no suitable implementation for this system: ' + repr(e))