clock.cc 25 KB

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