clock.cc 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  1. // Copyright 2017 The Abseil Authors.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // https://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include "absl/time/clock.h"
  15. #include "absl/base/attributes.h"
  16. #include "absl/base/optimization.h"
  17. #ifdef _WIN32
  18. #include <windows.h>
  19. #endif
  20. #include <algorithm>
  21. #include <atomic>
  22. #include <cerrno>
  23. #include <cstdint>
  24. #include <ctime>
  25. #include <limits>
  26. #include "absl/base/internal/spinlock.h"
  27. #include "absl/base/internal/unscaledcycleclock.h"
  28. #include "absl/base/macros.h"
  29. #include "absl/base/port.h"
  30. #include "absl/base/thread_annotations.h"
  31. namespace absl {
  32. ABSL_NAMESPACE_BEGIN
  33. Time Now() {
  34. // TODO(bww): Get a timespec instead so we don't have to divide.
  35. int64_t n = absl::GetCurrentTimeNanos();
  36. if (n >= 0) {
  37. return time_internal::FromUnixDuration(
  38. time_internal::MakeDuration(n / 1000000000, n % 1000000000 * 4));
  39. }
  40. return time_internal::FromUnixDuration(absl::Nanoseconds(n));
  41. }
  42. ABSL_NAMESPACE_END
  43. } // namespace absl
  44. // Decide if we should use the fast GetCurrentTimeNanos() algorithm based on the
  45. // cyclecounter, otherwise just get the time directly from the OS on every call.
  46. // By default, the fast algorithm based on the cyclecount is disabled because in
  47. // certain situations, for example, if the OS enters a "sleep" mode, it may
  48. // produce incorrect values immediately upon waking.
  49. // This can be chosen at compile-time via
  50. // -DABSL_USE_CYCLECLOCK_FOR_GET_CURRENT_TIME_NANOS=[0|1]
  51. #ifndef ABSL_USE_CYCLECLOCK_FOR_GET_CURRENT_TIME_NANOS
  52. #define ABSL_USE_CYCLECLOCK_FOR_GET_CURRENT_TIME_NANOS 0
  53. #endif
  54. #if defined(__APPLE__) || defined(_WIN32)
  55. #include "absl/time/internal/get_current_time_chrono.inc"
  56. #else
  57. #include "absl/time/internal/get_current_time_posix.inc"
  58. #endif
  59. // Allows override by test.
  60. #ifndef GET_CURRENT_TIME_NANOS_FROM_SYSTEM
  61. #define GET_CURRENT_TIME_NANOS_FROM_SYSTEM() \
  62. ::absl::time_internal::GetCurrentTimeNanosFromSystem()
  63. #endif
  64. #if !ABSL_USE_CYCLECLOCK_FOR_GET_CURRENT_TIME_NANOS
  65. namespace absl {
  66. ABSL_NAMESPACE_BEGIN
  67. int64_t GetCurrentTimeNanos() { return GET_CURRENT_TIME_NANOS_FROM_SYSTEM(); }
  68. ABSL_NAMESPACE_END
  69. } // namespace absl
  70. #else // Use the cyclecounter-based implementation below.
  71. // Allows override by test.
  72. #ifndef GET_CURRENT_TIME_NANOS_CYCLECLOCK_NOW
  73. #define GET_CURRENT_TIME_NANOS_CYCLECLOCK_NOW() \
  74. ::absl::time_internal::UnscaledCycleClockWrapperForGetCurrentTime::Now()
  75. #endif
  76. namespace absl {
  77. ABSL_NAMESPACE_BEGIN
  78. namespace time_internal {
  79. // On some processors, consecutive reads of the cycle counter may yield the
  80. // same value (weakly-increasing). In debug mode, clear the least significant
  81. // bits to discourage depending on a strictly-increasing Now() value.
  82. // In x86-64's debug mode, discourage depending on a strictly-increasing Now()
  83. // value.
  84. #if !defined(NDEBUG) && defined(__x86_64__)
  85. constexpr int64_t kCycleClockNowMask = ~int64_t{0xff};
  86. #else
  87. constexpr int64_t kCycleClockNowMask = ~int64_t{0};
  88. #endif
  89. // This is a friend wrapper around UnscaledCycleClock::Now()
  90. // (needed to access UnscaledCycleClock).
  91. class UnscaledCycleClockWrapperForGetCurrentTime {
  92. public:
  93. static int64_t Now() {
  94. return base_internal::UnscaledCycleClock::Now() & kCycleClockNowMask;
  95. }
  96. };
  97. } // namespace time_internal
  98. // uint64_t is used in this module to provide an extra bit in multiplications
  99. // ---------------------------------------------------------------------
  100. // An implementation of reader-write locks that use no atomic ops in the read
  101. // case. This is a generalization of Lamport's method for reading a multiword
  102. // clock. Increment a word on each write acquisition, using the low-order bit
  103. // as a spinlock; the word is the high word of the "clock". Readers read the
  104. // high word, then all other data, then the high word again, and repeat the
  105. // read if the reads of the high words yields different answers, or an odd
  106. // value (either case suggests possible interference from a writer).
  107. // Here we use a spinlock to ensure only one writer at a time, rather than
  108. // spinning on the bottom bit of the word to benefit from SpinLock
  109. // spin-delay tuning.
  110. // Acquire seqlock (*seq) and return the value to be written to unlock.
  111. static inline uint64_t SeqAcquire(std::atomic<uint64_t> *seq) {
  112. uint64_t x = seq->fetch_add(1, std::memory_order_relaxed);
  113. // We put a release fence between update to *seq and writes to shared data.
  114. // Thus all stores to shared data are effectively release operations and
  115. // update to *seq above cannot be re-ordered past any of them. Note that
  116. // this barrier is not for the fetch_add above. A release barrier for the
  117. // fetch_add would be before it, not after.
  118. std::atomic_thread_fence(std::memory_order_release);
  119. return x + 2; // original word plus 2
  120. }
  121. // Release seqlock (*seq) by writing x to it---a value previously returned by
  122. // SeqAcquire.
  123. static inline void SeqRelease(std::atomic<uint64_t> *seq, uint64_t x) {
  124. // The unlock store to *seq must have release ordering so that all
  125. // updates to shared data must finish before this store.
  126. seq->store(x, std::memory_order_release); // release lock for readers
  127. }
  128. // ---------------------------------------------------------------------
  129. // "nsscaled" is unit of time equal to a (2**kScale)th of a nanosecond.
  130. enum { kScale = 30 };
  131. // The minimum interval between samples of the time base.
  132. // We pick enough time to amortize the cost of the sample,
  133. // to get a reasonably accurate cycle counter rate reading,
  134. // and not so much that calculations will overflow 64-bits.
  135. static const uint64_t kMinNSBetweenSamples = 2000 << 20;
  136. // We require that kMinNSBetweenSamples shifted by kScale
  137. // have at least a bit left over for 64-bit calculations.
  138. static_assert(((kMinNSBetweenSamples << (kScale + 1)) >> (kScale + 1)) ==
  139. kMinNSBetweenSamples,
  140. "cannot represent kMaxBetweenSamplesNSScaled");
  141. // data from a sample of the kernel's time value
  142. struct TimeSampleAtomic {
  143. std::atomic<uint64_t> raw_ns{0}; // raw kernel time
  144. std::atomic<uint64_t> base_ns{0}; // our estimate of time
  145. std::atomic<uint64_t> base_cycles{0}; // cycle counter reading
  146. std::atomic<uint64_t> nsscaled_per_cycle{0}; // cycle period
  147. // cycles before we'll sample again (a scaled reciprocal of the period,
  148. // to avoid a division on the fast path).
  149. std::atomic<uint64_t> min_cycles_per_sample{0};
  150. };
  151. // Same again, but with non-atomic types
  152. struct TimeSample {
  153. uint64_t raw_ns = 0; // raw kernel time
  154. uint64_t base_ns = 0; // our estimate of time
  155. uint64_t base_cycles = 0; // cycle counter reading
  156. uint64_t nsscaled_per_cycle = 0; // cycle period
  157. uint64_t min_cycles_per_sample = 0; // approx cycles before next sample
  158. };
  159. struct ABSL_CACHELINE_ALIGNED TimeState {
  160. std::atomic<uint64_t> seq{0};
  161. TimeSampleAtomic last_sample; // the last sample; under seq
  162. // The following counters are used only by the test code.
  163. int64_t stats_initializations{0};
  164. int64_t stats_reinitializations{0};
  165. int64_t stats_calibrations{0};
  166. int64_t stats_slow_paths{0};
  167. int64_t stats_fast_slow_paths{0};
  168. uint64_t last_now_cycles ABSL_GUARDED_BY(lock){0};
  169. // Used by GetCurrentTimeNanosFromKernel().
  170. // We try to read clock values at about the same time as the kernel clock.
  171. // This value gets adjusted up or down as estimate of how long that should
  172. // take, so we can reject attempts that take unusually long.
  173. std::atomic<uint64_t> approx_syscall_time_in_cycles{10 * 1000};
  174. // Number of times in a row we've seen a kernel time call take substantially
  175. // less than approx_syscall_time_in_cycles.
  176. std::atomic<uint32_t> kernel_time_seen_smaller{0};
  177. // A reader-writer lock protecting the static locations below.
  178. // See SeqAcquire() and SeqRelease() above.
  179. absl::base_internal::SpinLock lock{absl::kConstInit,
  180. base_internal::SCHEDULE_KERNEL_ONLY};
  181. };
  182. ABSL_CONST_INIT static TimeState time_state;
  183. // Return the time in ns as told by the kernel interface. Place in *cycleclock
  184. // the value of the cycleclock at about the time of the syscall.
  185. // This call represents the time base that this module synchronizes to.
  186. // Ensures that *cycleclock does not step back by up to (1 << 16) from
  187. // last_cycleclock, to discard small backward counter steps. (Larger steps are
  188. // assumed to be complete resyncs, which shouldn't happen. If they do, a full
  189. // reinitialization of the outer algorithm should occur.)
  190. static int64_t GetCurrentTimeNanosFromKernel(uint64_t last_cycleclock,
  191. uint64_t *cycleclock)
  192. ABSL_EXCLUSIVE_LOCKS_REQUIRED(time_state.lock) {
  193. uint64_t local_approx_syscall_time_in_cycles = // local copy
  194. time_state.approx_syscall_time_in_cycles.load(std::memory_order_relaxed);
  195. int64_t current_time_nanos_from_system;
  196. uint64_t before_cycles;
  197. uint64_t after_cycles;
  198. uint64_t elapsed_cycles;
  199. int loops = 0;
  200. do {
  201. before_cycles =
  202. static_cast<uint64_t>(GET_CURRENT_TIME_NANOS_CYCLECLOCK_NOW());
  203. current_time_nanos_from_system = GET_CURRENT_TIME_NANOS_FROM_SYSTEM();
  204. after_cycles =
  205. static_cast<uint64_t>(GET_CURRENT_TIME_NANOS_CYCLECLOCK_NOW());
  206. // elapsed_cycles is unsigned, so is large on overflow
  207. elapsed_cycles = after_cycles - before_cycles;
  208. if (elapsed_cycles >= local_approx_syscall_time_in_cycles &&
  209. ++loops == 20) { // clock changed frequencies? Back off.
  210. loops = 0;
  211. if (local_approx_syscall_time_in_cycles < 1000 * 1000) {
  212. local_approx_syscall_time_in_cycles =
  213. (local_approx_syscall_time_in_cycles + 1) << 1;
  214. }
  215. time_state.approx_syscall_time_in_cycles.store(
  216. local_approx_syscall_time_in_cycles, std::memory_order_relaxed);
  217. }
  218. } while (elapsed_cycles >= local_approx_syscall_time_in_cycles ||
  219. last_cycleclock - after_cycles < (static_cast<uint64_t>(1) << 16));
  220. // Adjust approx_syscall_time_in_cycles to be within a factor of 2
  221. // of the typical time to execute one iteration of the loop above.
  222. if ((local_approx_syscall_time_in_cycles >> 1) < elapsed_cycles) {
  223. // measured time is no smaller than half current approximation
  224. time_state.kernel_time_seen_smaller.store(0, std::memory_order_relaxed);
  225. } else if (time_state.kernel_time_seen_smaller.fetch_add(
  226. 1, std::memory_order_relaxed) >= 3) {
  227. // smaller delays several times in a row; reduce approximation by 12.5%
  228. const uint64_t new_approximation =
  229. local_approx_syscall_time_in_cycles -
  230. (local_approx_syscall_time_in_cycles >> 3);
  231. time_state.approx_syscall_time_in_cycles.store(new_approximation,
  232. std::memory_order_relaxed);
  233. time_state.kernel_time_seen_smaller.store(0, std::memory_order_relaxed);
  234. }
  235. *cycleclock = after_cycles;
  236. return current_time_nanos_from_system;
  237. }
  238. static int64_t GetCurrentTimeNanosSlowPath() ABSL_ATTRIBUTE_COLD;
  239. // Read the contents of *atomic into *sample.
  240. // Each field is read atomically, but to maintain atomicity between fields,
  241. // the access must be done under a lock.
  242. static void ReadTimeSampleAtomic(const struct TimeSampleAtomic *atomic,
  243. struct TimeSample *sample) {
  244. sample->base_ns = atomic->base_ns.load(std::memory_order_relaxed);
  245. sample->base_cycles = atomic->base_cycles.load(std::memory_order_relaxed);
  246. sample->nsscaled_per_cycle =
  247. atomic->nsscaled_per_cycle.load(std::memory_order_relaxed);
  248. sample->min_cycles_per_sample =
  249. atomic->min_cycles_per_sample.load(std::memory_order_relaxed);
  250. sample->raw_ns = atomic->raw_ns.load(std::memory_order_relaxed);
  251. }
  252. // Public routine.
  253. // Algorithm: We wish to compute real time from a cycle counter. In normal
  254. // operation, we construct a piecewise linear approximation to the kernel time
  255. // source, using the cycle counter value. The start of each line segment is at
  256. // the same point as the end of the last, but may have a different slope (that
  257. // is, a different idea of the cycle counter frequency). Every couple of
  258. // seconds, the kernel time source is sampled and compared with the current
  259. // approximation. A new slope is chosen that, if followed for another couple
  260. // of seconds, will correct the error at the current position. The information
  261. // for a sample is in the "last_sample" struct. The linear approximation is
  262. // estimated_time = last_sample.base_ns +
  263. // last_sample.ns_per_cycle * (counter_reading - last_sample.base_cycles)
  264. // (ns_per_cycle is actually stored in different units and scaled, to avoid
  265. // overflow). The base_ns of the next linear approximation is the
  266. // estimated_time using the last approximation; the base_cycles is the cycle
  267. // counter value at that time; the ns_per_cycle is the number of ns per cycle
  268. // measured since the last sample, but adjusted so that most of the difference
  269. // between the estimated_time and the kernel time will be corrected by the
  270. // estimated time to the next sample. In normal operation, this algorithm
  271. // relies on:
  272. // - the cycle counter and kernel time rates not changing a lot in a few
  273. // seconds.
  274. // - the client calling into the code often compared to a couple of seconds, so
  275. // the time to the next correction can be estimated.
  276. // Any time ns_per_cycle is not known, a major error is detected, or the
  277. // assumption about frequent calls is violated, the implementation returns the
  278. // kernel time. It records sufficient data that a linear approximation can
  279. // resume a little later.
  280. int64_t GetCurrentTimeNanos() {
  281. // read the data from the "last_sample" struct (but don't need raw_ns yet)
  282. // The reads of "seq" and test of the values emulate a reader lock.
  283. uint64_t base_ns;
  284. uint64_t base_cycles;
  285. uint64_t nsscaled_per_cycle;
  286. uint64_t min_cycles_per_sample;
  287. uint64_t seq_read0;
  288. uint64_t seq_read1;
  289. // If we have enough information to interpolate, the value returned will be
  290. // derived from this cycleclock-derived time estimate. On some platforms
  291. // (POWER) the function to retrieve this value has enough complexity to
  292. // contribute to register pressure - reading it early before initializing
  293. // the other pieces of the calculation minimizes spill/restore instructions,
  294. // minimizing icache cost.
  295. uint64_t now_cycles =
  296. static_cast<uint64_t>(GET_CURRENT_TIME_NANOS_CYCLECLOCK_NOW());
  297. // Acquire pairs with the barrier in SeqRelease - if this load sees that
  298. // store, the shared-data reads necessarily see that SeqRelease's updates
  299. // to the same shared data.
  300. seq_read0 = time_state.seq.load(std::memory_order_acquire);
  301. base_ns = time_state.last_sample.base_ns.load(std::memory_order_relaxed);
  302. base_cycles =
  303. time_state.last_sample.base_cycles.load(std::memory_order_relaxed);
  304. nsscaled_per_cycle =
  305. time_state.last_sample.nsscaled_per_cycle.load(std::memory_order_relaxed);
  306. min_cycles_per_sample = time_state.last_sample.min_cycles_per_sample.load(
  307. std::memory_order_relaxed);
  308. // This acquire fence pairs with the release fence in SeqAcquire. Since it
  309. // is sequenced between reads of shared data and seq_read1, the reads of
  310. // shared data are effectively acquiring.
  311. std::atomic_thread_fence(std::memory_order_acquire);
  312. // The shared-data reads are effectively acquire ordered, and the
  313. // shared-data writes are effectively release ordered. Therefore if our
  314. // shared-data reads see any of a particular update's shared-data writes,
  315. // seq_read1 is guaranteed to see that update's SeqAcquire.
  316. seq_read1 = time_state.seq.load(std::memory_order_relaxed);
  317. // Fast path. Return if min_cycles_per_sample has not yet elapsed since the
  318. // last sample, and we read a consistent sample. The fast path activates
  319. // only when min_cycles_per_sample is non-zero, which happens when we get an
  320. // estimate for the cycle time. The predicate will fail if now_cycles <
  321. // base_cycles, or if some other thread is in the slow path.
  322. //
  323. // Since we now read now_cycles before base_ns, it is possible for now_cycles
  324. // to be less than base_cycles (if we were interrupted between those loads and
  325. // last_sample was updated). This is harmless, because delta_cycles will wrap
  326. // and report a time much much bigger than min_cycles_per_sample. In that case
  327. // we will take the slow path.
  328. uint64_t delta_cycles;
  329. if (seq_read0 == seq_read1 && (seq_read0 & 1) == 0 &&
  330. (delta_cycles = now_cycles - base_cycles) < min_cycles_per_sample) {
  331. return static_cast<int64_t>(
  332. base_ns + ((delta_cycles * nsscaled_per_cycle) >> kScale));
  333. }
  334. return GetCurrentTimeNanosSlowPath();
  335. }
  336. // Return (a << kScale)/b.
  337. // Zero is returned if b==0. Scaling is performed internally to
  338. // preserve precision without overflow.
  339. static uint64_t SafeDivideAndScale(uint64_t a, uint64_t b) {
  340. // Find maximum safe_shift so that
  341. // 0 <= safe_shift <= kScale and (a << safe_shift) does not overflow.
  342. int safe_shift = kScale;
  343. while (((a << safe_shift) >> safe_shift) != a) {
  344. safe_shift--;
  345. }
  346. uint64_t scaled_b = b >> (kScale - safe_shift);
  347. uint64_t quotient = 0;
  348. if (scaled_b != 0) {
  349. quotient = (a << safe_shift) / scaled_b;
  350. }
  351. return quotient;
  352. }
  353. static uint64_t UpdateLastSample(
  354. uint64_t now_cycles, uint64_t now_ns, uint64_t delta_cycles,
  355. const struct TimeSample *sample) ABSL_ATTRIBUTE_COLD;
  356. // The slow path of GetCurrentTimeNanos(). This is taken while gathering
  357. // initial samples, when enough time has elapsed since the last sample, and if
  358. // any other thread is writing to last_sample.
  359. //
  360. // Manually mark this 'noinline' to minimize stack frame size of the fast
  361. // path. Without this, sometimes a compiler may inline this big block of code
  362. // into the fast path. That causes lots of register spills and reloads that
  363. // are unnecessary unless the slow path is taken.
  364. //
  365. // TODO(absl-team): Remove this attribute when our compiler is smart enough
  366. // to do the right thing.
  367. ABSL_ATTRIBUTE_NOINLINE
  368. static int64_t GetCurrentTimeNanosSlowPath()
  369. ABSL_LOCKS_EXCLUDED(time_state.lock) {
  370. // Serialize access to slow-path. Fast-path readers are not blocked yet, and
  371. // code below must not modify last_sample until the seqlock is acquired.
  372. time_state.lock.Lock();
  373. // Sample the kernel time base. This is the definition of
  374. // "now" if we take the slow path.
  375. uint64_t now_cycles;
  376. uint64_t now_ns = static_cast<uint64_t>(
  377. GetCurrentTimeNanosFromKernel(time_state.last_now_cycles, &now_cycles));
  378. time_state.last_now_cycles = now_cycles;
  379. uint64_t estimated_base_ns;
  380. // ----------
  381. // Read the "last_sample" values again; this time holding the write lock.
  382. struct TimeSample sample;
  383. ReadTimeSampleAtomic(&time_state.last_sample, &sample);
  384. // ----------
  385. // Try running the fast path again; another thread may have updated the
  386. // sample between our run of the fast path and the sample we just read.
  387. uint64_t delta_cycles = now_cycles - sample.base_cycles;
  388. if (delta_cycles < sample.min_cycles_per_sample) {
  389. // Another thread updated the sample. This path does not take the seqlock
  390. // so that blocked readers can make progress without blocking new readers.
  391. estimated_base_ns = sample.base_ns +
  392. ((delta_cycles * sample.nsscaled_per_cycle) >> kScale);
  393. time_state.stats_fast_slow_paths++;
  394. } else {
  395. estimated_base_ns =
  396. UpdateLastSample(now_cycles, now_ns, delta_cycles, &sample);
  397. }
  398. time_state.lock.Unlock();
  399. return static_cast<int64_t>(estimated_base_ns);
  400. }
  401. // Main part of the algorithm. Locks out readers, updates the approximation
  402. // using the new sample from the kernel, and stores the result in last_sample
  403. // for readers. Returns the new estimated time.
  404. static uint64_t UpdateLastSample(uint64_t now_cycles, uint64_t now_ns,
  405. uint64_t delta_cycles,
  406. const struct TimeSample *sample)
  407. ABSL_EXCLUSIVE_LOCKS_REQUIRED(time_state.lock) {
  408. uint64_t estimated_base_ns = now_ns;
  409. uint64_t lock_value =
  410. SeqAcquire(&time_state.seq); // acquire seqlock to block readers
  411. // The 5s in the next if-statement limits the time for which we will trust
  412. // the cycle counter and our last sample to give a reasonable result.
  413. // Errors in the rate of the source clock can be multiplied by the ratio
  414. // between this limit and kMinNSBetweenSamples.
  415. if (sample->raw_ns == 0 || // no recent sample, or clock went backwards
  416. sample->raw_ns + static_cast<uint64_t>(5) * 1000 * 1000 * 1000 < now_ns ||
  417. now_ns < sample->raw_ns || now_cycles < sample->base_cycles) {
  418. // record this sample, and forget any previously known slope.
  419. time_state.last_sample.raw_ns.store(now_ns, std::memory_order_relaxed);
  420. time_state.last_sample.base_ns.store(estimated_base_ns,
  421. std::memory_order_relaxed);
  422. time_state.last_sample.base_cycles.store(now_cycles,
  423. std::memory_order_relaxed);
  424. time_state.last_sample.nsscaled_per_cycle.store(0,
  425. std::memory_order_relaxed);
  426. time_state.last_sample.min_cycles_per_sample.store(
  427. 0, std::memory_order_relaxed);
  428. time_state.stats_initializations++;
  429. } else if (sample->raw_ns + 500 * 1000 * 1000 < now_ns &&
  430. sample->base_cycles + 50 < now_cycles) {
  431. // Enough time has passed to compute the cycle time.
  432. if (sample->nsscaled_per_cycle != 0) { // Have a cycle time estimate.
  433. // Compute time from counter reading, but avoiding overflow
  434. // delta_cycles may be larger than on the fast path.
  435. uint64_t estimated_scaled_ns;
  436. int s = -1;
  437. do {
  438. s++;
  439. estimated_scaled_ns = (delta_cycles >> s) * sample->nsscaled_per_cycle;
  440. } while (estimated_scaled_ns / sample->nsscaled_per_cycle !=
  441. (delta_cycles >> s));
  442. estimated_base_ns = sample->base_ns +
  443. (estimated_scaled_ns >> (kScale - s));
  444. }
  445. // Compute the assumed cycle time kMinNSBetweenSamples ns into the future
  446. // assuming the cycle counter rate stays the same as the last interval.
  447. uint64_t ns = now_ns - sample->raw_ns;
  448. uint64_t measured_nsscaled_per_cycle = SafeDivideAndScale(ns, delta_cycles);
  449. uint64_t assumed_next_sample_delta_cycles =
  450. SafeDivideAndScale(kMinNSBetweenSamples, measured_nsscaled_per_cycle);
  451. // Estimate low by this much.
  452. int64_t diff_ns = static_cast<int64_t>(now_ns - estimated_base_ns);
  453. // We want to set nsscaled_per_cycle so that our estimate of the ns time
  454. // at the assumed cycle time is the assumed ns time.
  455. // That is, we want to set nsscaled_per_cycle so:
  456. // kMinNSBetweenSamples + diff_ns ==
  457. // (assumed_next_sample_delta_cycles * nsscaled_per_cycle) >> kScale
  458. // But we wish to damp oscillations, so instead correct only most
  459. // of our current error, by solving:
  460. // kMinNSBetweenSamples + diff_ns - (diff_ns / 16) ==
  461. // (assumed_next_sample_delta_cycles * nsscaled_per_cycle) >> kScale
  462. ns = static_cast<uint64_t>(static_cast<int64_t>(kMinNSBetweenSamples) +
  463. diff_ns - (diff_ns / 16));
  464. uint64_t new_nsscaled_per_cycle =
  465. SafeDivideAndScale(ns, assumed_next_sample_delta_cycles);
  466. if (new_nsscaled_per_cycle != 0 &&
  467. diff_ns < 100 * 1000 * 1000 && -diff_ns < 100 * 1000 * 1000) {
  468. // record the cycle time measurement
  469. time_state.last_sample.nsscaled_per_cycle.store(
  470. new_nsscaled_per_cycle, std::memory_order_relaxed);
  471. uint64_t new_min_cycles_per_sample =
  472. SafeDivideAndScale(kMinNSBetweenSamples, new_nsscaled_per_cycle);
  473. time_state.last_sample.min_cycles_per_sample.store(
  474. new_min_cycles_per_sample, std::memory_order_relaxed);
  475. time_state.stats_calibrations++;
  476. } else { // something went wrong; forget the slope
  477. time_state.last_sample.nsscaled_per_cycle.store(
  478. 0, std::memory_order_relaxed);
  479. time_state.last_sample.min_cycles_per_sample.store(
  480. 0, std::memory_order_relaxed);
  481. estimated_base_ns = now_ns;
  482. time_state.stats_reinitializations++;
  483. }
  484. time_state.last_sample.raw_ns.store(now_ns, std::memory_order_relaxed);
  485. time_state.last_sample.base_ns.store(estimated_base_ns,
  486. std::memory_order_relaxed);
  487. time_state.last_sample.base_cycles.store(now_cycles,
  488. std::memory_order_relaxed);
  489. } else {
  490. // have a sample, but no slope; waiting for enough time for a calibration
  491. time_state.stats_slow_paths++;
  492. }
  493. SeqRelease(&time_state.seq, lock_value); // release the readers
  494. return estimated_base_ns;
  495. }
  496. ABSL_NAMESPACE_END
  497. } // namespace absl
  498. #endif // ABSL_USE_CYCLECLOCK_FOR_GET_CURRENT_TIME_NANOS
  499. namespace absl {
  500. ABSL_NAMESPACE_BEGIN
  501. namespace {
  502. // Returns the maximum duration that SleepOnce() can sleep for.
  503. constexpr absl::Duration MaxSleep() {
  504. #ifdef _WIN32
  505. // Windows Sleep() takes unsigned long argument in milliseconds.
  506. return absl::Milliseconds(
  507. std::numeric_limits<unsigned long>::max()); // NOLINT(runtime/int)
  508. #else
  509. return absl::Seconds(std::numeric_limits<time_t>::max());
  510. #endif
  511. }
  512. // Sleeps for the given duration.
  513. // REQUIRES: to_sleep <= MaxSleep().
  514. void SleepOnce(absl::Duration to_sleep) {
  515. #ifdef _WIN32
  516. Sleep(static_cast<DWORD>(to_sleep / absl::Milliseconds(1)));
  517. #else
  518. struct timespec sleep_time = absl::ToTimespec(to_sleep);
  519. while (nanosleep(&sleep_time, &sleep_time) != 0 && errno == EINTR) {
  520. // Ignore signals and wait for the full interval to elapse.
  521. }
  522. #endif
  523. }
  524. } // namespace
  525. ABSL_NAMESPACE_END
  526. } // namespace absl
  527. extern "C" {
  528. ABSL_ATTRIBUTE_WEAK void ABSL_INTERNAL_C_SYMBOL(AbslInternalSleepFor)(
  529. absl::Duration duration) {
  530. while (duration > absl::ZeroDuration()) {
  531. absl::Duration to_sleep = std::min(duration, absl::MaxSleep());
  532. absl::SleepOnce(to_sleep);
  533. duration -= to_sleep;
  534. }
  535. }
  536. } // extern "C"