clock.cpp 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. /*
  2. Copyright (c) 2007-2016 Contributors as noted in the AUTHORS file
  3. This file is part of libzmq, the ZeroMQ core engine in C++.
  4. libzmq is free software; you can redistribute it and/or modify it under
  5. the terms of the GNU Lesser General Public License (LGPL) as published
  6. by the Free Software Foundation; either version 3 of the License, or
  7. (at your option) any later version.
  8. As a special exception, the Contributors give you permission to link
  9. this library with independent modules to produce an executable,
  10. regardless of the license terms of these independent modules, and to
  11. copy and distribute the resulting executable under terms of your choice,
  12. provided that you also meet, for each linked independent module, the
  13. terms and conditions of the license of that module. An independent
  14. module is a module which is not derived from or based on this library.
  15. If you modify this library, you must extend this exception to your
  16. version of the library.
  17. libzmq is distributed in the hope that it will be useful, but WITHOUT
  18. ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  19. FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
  20. License for more details.
  21. You should have received a copy of the GNU Lesser General Public License
  22. along with this program. If not, see <http://www.gnu.org/licenses/>.
  23. */
  24. #include "precompiled.hpp"
  25. #include "clock.hpp"
  26. #include "likely.hpp"
  27. #include "config.hpp"
  28. #include "err.hpp"
  29. #include "mutex.hpp"
  30. #include <stddef.h>
  31. #if defined _MSC_VER
  32. #if defined _WIN32_WCE
  33. #include <cmnintrin.h>
  34. #else
  35. #include <intrin.h>
  36. #endif
  37. #endif
  38. #if !defined ZMQ_HAVE_WINDOWS
  39. #include <sys/time.h>
  40. #endif
  41. #if defined HAVE_CLOCK_GETTIME || defined HAVE_GETHRTIME
  42. #include <time.h>
  43. #endif
  44. #if defined ZMQ_HAVE_VXWORKS
  45. #include "timers.h"
  46. #endif
  47. #if defined ZMQ_HAVE_OSX
  48. int alt_clock_gettime (int clock_id, timespec *ts)
  49. {
  50. clock_serv_t cclock;
  51. mach_timespec_t mts;
  52. host_get_clock_service (mach_host_self (), clock_id, &cclock);
  53. clock_get_time (cclock, &mts);
  54. mach_port_deallocate (mach_task_self (), cclock);
  55. ts->tv_sec = mts.tv_sec;
  56. ts->tv_nsec = mts.tv_nsec;
  57. return 0;
  58. }
  59. #endif
  60. #ifdef ZMQ_HAVE_WINDOWS
  61. typedef ULONGLONG (*f_compatible_get_tick_count64) ();
  62. static zmq::mutex_t compatible_get_tick_count64_mutex;
  63. ULONGLONG compatible_get_tick_count64 ()
  64. {
  65. #ifdef ZMQ_HAVE_WINDOWS_UWP
  66. const ULONGLONG result = ::GetTickCount64 ();
  67. return result;
  68. #else
  69. zmq::scoped_lock_t locker (compatible_get_tick_count64_mutex);
  70. static DWORD s_wrap = 0;
  71. static DWORD s_last_tick = 0;
  72. const DWORD current_tick = ::GetTickCount ();
  73. if (current_tick < s_last_tick)
  74. ++s_wrap;
  75. s_last_tick = current_tick;
  76. const ULONGLONG result = (static_cast<ULONGLONG> (s_wrap) << 32)
  77. + static_cast<ULONGLONG> (current_tick);
  78. return result;
  79. #endif
  80. }
  81. f_compatible_get_tick_count64 init_compatible_get_tick_count64 ()
  82. {
  83. f_compatible_get_tick_count64 func = NULL;
  84. #if !defined ZMQ_HAVE_WINDOWS_UWP
  85. const HMODULE module = ::LoadLibraryA ("Kernel32.dll");
  86. if (module != NULL)
  87. func = reinterpret_cast<f_compatible_get_tick_count64> (
  88. ::GetProcAddress (module, "GetTickCount64"));
  89. #endif
  90. if (func == NULL)
  91. func = compatible_get_tick_count64;
  92. #if !defined ZMQ_HAVE_WINDOWS_UWP
  93. if (module != NULL)
  94. ::FreeLibrary (module);
  95. #endif
  96. return func;
  97. }
  98. static f_compatible_get_tick_count64 my_get_tick_count64 =
  99. init_compatible_get_tick_count64 ();
  100. #endif
  101. const uint64_t usecs_per_msec = 1000;
  102. const uint64_t usecs_per_sec = 1000000;
  103. const uint64_t nsecs_per_usec = 1000;
  104. zmq::clock_t::clock_t () :
  105. _last_tsc (rdtsc ()),
  106. #ifdef ZMQ_HAVE_WINDOWS
  107. _last_time (static_cast<uint64_t> ((*my_get_tick_count64) ()))
  108. #else
  109. _last_time (now_us () / usecs_per_msec)
  110. #endif
  111. {
  112. }
  113. uint64_t zmq::clock_t::now_us ()
  114. {
  115. #if defined ZMQ_HAVE_WINDOWS
  116. // Get the high resolution counter's accuracy.
  117. // While QueryPerformanceFrequency only needs to be called once, since its
  118. // value does not change during runtime, we query it here since this is a
  119. // static function. It might make sense to cache it, though.
  120. LARGE_INTEGER ticks_per_second;
  121. QueryPerformanceFrequency (&ticks_per_second);
  122. // What time is it?
  123. LARGE_INTEGER tick;
  124. QueryPerformanceCounter (&tick);
  125. // Convert the tick number into the number of seconds
  126. // since the system was started.
  127. const double ticks_div =
  128. static_cast<double> (ticks_per_second.QuadPart) / usecs_per_sec;
  129. return static_cast<uint64_t> (tick.QuadPart / ticks_div);
  130. #elif defined HAVE_CLOCK_GETTIME \
  131. && (defined CLOCK_MONOTONIC || defined ZMQ_HAVE_VXWORKS)
  132. // Use POSIX clock_gettime function to get precise monotonic time.
  133. struct timespec tv;
  134. #if defined ZMQ_HAVE_OSX \
  135. && __MAC_OS_X_VERSION_MIN_REQUIRED < 101200 // less than macOS 10.12
  136. int rc = alt_clock_gettime (SYSTEM_CLOCK, &tv);
  137. #else
  138. int rc = clock_gettime (CLOCK_MONOTONIC, &tv);
  139. #endif
  140. // Fix case where system has clock_gettime but CLOCK_MONOTONIC is not supported.
  141. // This should be a configuration check, but I looked into it and writing an
  142. // AC_FUNC_CLOCK_MONOTONIC seems beyond my powers.
  143. if (rc != 0) {
  144. #ifndef ZMQ_HAVE_VXWORKS
  145. // Use POSIX gettimeofday function to get precise time.
  146. struct timeval tv;
  147. int rc = gettimeofday (&tv, NULL);
  148. errno_assert (rc == 0);
  149. return tv.tv_sec * usecs_per_sec + tv.tv_usec;
  150. #endif
  151. }
  152. return tv.tv_sec * usecs_per_sec + tv.tv_nsec / nsecs_per_usec;
  153. #elif defined HAVE_GETHRTIME
  154. return gethrtime () / nsecs_per_usec;
  155. #else
  156. // Use POSIX gettimeofday function to get precise time.
  157. struct timeval tv;
  158. int rc = gettimeofday (&tv, NULL);
  159. errno_assert (rc == 0);
  160. return tv.tv_sec * usecs_per_sec + tv.tv_usec;
  161. #endif
  162. }
  163. uint64_t zmq::clock_t::now_ms ()
  164. {
  165. const uint64_t tsc = rdtsc ();
  166. // If TSC is not supported, get precise time and chop off the microseconds.
  167. if (!tsc) {
  168. #ifdef ZMQ_HAVE_WINDOWS
  169. // Under Windows, now_us is not so reliable since QueryPerformanceCounter
  170. // does not guarantee that it will use a hardware that offers a monotonic timer.
  171. // So, lets use GetTickCount when GetTickCount64 is not available with an workaround
  172. // to its 32 bit limitation.
  173. return static_cast<uint64_t> ((*my_get_tick_count64) ());
  174. #else
  175. return now_us () / usecs_per_msec;
  176. #endif
  177. }
  178. // If TSC haven't jumped back (in case of migration to a different
  179. // CPU core) and if not too much time elapsed since last measurement,
  180. // we can return cached time value.
  181. if (likely (tsc - _last_tsc <= (clock_precision / 2) && tsc >= _last_tsc))
  182. return _last_time;
  183. _last_tsc = tsc;
  184. #ifdef ZMQ_HAVE_WINDOWS
  185. _last_time = static_cast<uint64_t> ((*my_get_tick_count64) ());
  186. #else
  187. _last_time = now_us () / usecs_per_msec;
  188. #endif
  189. return _last_time;
  190. }
  191. uint64_t zmq::clock_t::rdtsc ()
  192. {
  193. #if (defined _MSC_VER && (defined _M_IX86 || defined _M_X64))
  194. return __rdtsc ();
  195. #elif (defined __GNUC__ && (defined __i386__ || defined __x86_64__))
  196. uint32_t low, high;
  197. __asm__ volatile("rdtsc" : "=a"(low), "=d"(high));
  198. return static_cast<uint64_t> (high) << 32 | low;
  199. #elif (defined __SUNPRO_CC && (__SUNPRO_CC >= 0x5100) \
  200. && (defined __i386 || defined __amd64 || defined __x86_64))
  201. union
  202. {
  203. uint64_t u64val;
  204. uint32_t u32val[2];
  205. } tsc;
  206. asm("rdtsc" : "=a"(tsc.u32val[0]), "=d"(tsc.u32val[1]));
  207. return tsc.u64val;
  208. #elif defined(__s390__)
  209. uint64_t tsc;
  210. asm("\tstck\t%0\n" : "=Q"(tsc) : : "cc");
  211. return tsc;
  212. #else
  213. struct timespec ts;
  214. #if defined ZMQ_HAVE_OSX \
  215. && __MAC_OS_X_VERSION_MIN_REQUIRED < 101200 // less than macOS 10.12
  216. alt_clock_gettime (SYSTEM_CLOCK, &ts);
  217. #else
  218. clock_gettime (CLOCK_MONOTONIC, &ts);
  219. #endif
  220. return static_cast<uint64_t> (ts.tv_sec) * nsecs_per_usec * usecs_per_sec
  221. + ts.tv_nsec;
  222. #endif
  223. }