monotonic.py 7.7 KB

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