clock.cc 26 KB

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