clock.cc
Go to the documentation of this file.
00001 // Copyright 2017 The Abseil Authors.
00002 //
00003 // Licensed under the Apache License, Version 2.0 (the "License");
00004 // you may not use this file except in compliance with the License.
00005 // You may obtain a copy of the License at
00006 //
00007 //      https://www.apache.org/licenses/LICENSE-2.0
00008 //
00009 // Unless required by applicable law or agreed to in writing, software
00010 // distributed under the License is distributed on an "AS IS" BASIS,
00011 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
00012 // See the License for the specific language governing permissions and
00013 // limitations under the License.
00014 
00015 #include "absl/time/clock.h"
00016 
00017 #include "absl/base/attributes.h"
00018 
00019 #ifdef _WIN32
00020 #include <windows.h>
00021 #endif
00022 
00023 #include <algorithm>
00024 #include <atomic>
00025 #include <cerrno>
00026 #include <cstdint>
00027 #include <ctime>
00028 #include <limits>
00029 
00030 #include "absl/base/internal/spinlock.h"
00031 #include "absl/base/internal/unscaledcycleclock.h"
00032 #include "absl/base/macros.h"
00033 #include "absl/base/port.h"
00034 #include "absl/base/thread_annotations.h"
00035 
00036 namespace absl {
00037 Time Now() {
00038   // TODO(bww): Get a timespec instead so we don't have to divide.
00039   int64_t n = absl::GetCurrentTimeNanos();
00040   if (n >= 0) {
00041     return time_internal::FromUnixDuration(
00042         time_internal::MakeDuration(n / 1000000000, n % 1000000000 * 4));
00043   }
00044   return time_internal::FromUnixDuration(absl::Nanoseconds(n));
00045 }
00046 }  // namespace absl
00047 
00048 // Decide if we should use the fast GetCurrentTimeNanos() algorithm
00049 // based on the cyclecounter, otherwise just get the time directly
00050 // from the OS on every call. This can be chosen at compile-time via
00051 // -DABSL_USE_CYCLECLOCK_FOR_GET_CURRENT_TIME_NANOS=[0|1]
00052 #ifndef ABSL_USE_CYCLECLOCK_FOR_GET_CURRENT_TIME_NANOS
00053 #if ABSL_USE_UNSCALED_CYCLECLOCK
00054 #define ABSL_USE_CYCLECLOCK_FOR_GET_CURRENT_TIME_NANOS 1
00055 #else
00056 #define ABSL_USE_CYCLECLOCK_FOR_GET_CURRENT_TIME_NANOS 0
00057 #endif
00058 #endif
00059 
00060 #if defined(__APPLE__) || defined(_WIN32)
00061 #include "absl/time/internal/get_current_time_chrono.inc"
00062 #else
00063 #include "absl/time/internal/get_current_time_posix.inc"
00064 #endif
00065 
00066 // Allows override by test.
00067 #ifndef GET_CURRENT_TIME_NANOS_FROM_SYSTEM
00068 #define GET_CURRENT_TIME_NANOS_FROM_SYSTEM() \
00069   ::absl::time_internal::GetCurrentTimeNanosFromSystem()
00070 #endif
00071 
00072 #if !ABSL_USE_CYCLECLOCK_FOR_GET_CURRENT_TIME_NANOS
00073 namespace absl {
00074 int64_t GetCurrentTimeNanos() {
00075   return GET_CURRENT_TIME_NANOS_FROM_SYSTEM();
00076 }
00077 }  // namespace absl
00078 #else  // Use the cyclecounter-based implementation below.
00079 
00080 // Allows override by test.
00081 #ifndef GET_CURRENT_TIME_NANOS_CYCLECLOCK_NOW
00082 #define GET_CURRENT_TIME_NANOS_CYCLECLOCK_NOW() \
00083   ::absl::time_internal::UnscaledCycleClockWrapperForGetCurrentTime::Now()
00084 #endif
00085 
00086 // The following counters are used only by the test code.
00087 static int64_t stats_initializations;
00088 static int64_t stats_reinitializations;
00089 static int64_t stats_calibrations;
00090 static int64_t stats_slow_paths;
00091 static int64_t stats_fast_slow_paths;
00092 
00093 namespace absl {
00094 namespace time_internal {
00095 // This is a friend wrapper around UnscaledCycleClock::Now()
00096 // (needed to access UnscaledCycleClock).
00097 class UnscaledCycleClockWrapperForGetCurrentTime {
00098  public:
00099   static int64_t Now() { return base_internal::UnscaledCycleClock::Now(); }
00100 };
00101 }  // namespace time_internal
00102 
00103 // uint64_t is used in this module to provide an extra bit in multiplications
00104 
00105 // Return the time in ns as told by the kernel interface.  Place in *cycleclock
00106 // the value of the cycleclock at about the time of the syscall.
00107 // This call represents the time base that this module synchronizes to.
00108 // Ensures that *cycleclock does not step back by up to (1 << 16) from
00109 // last_cycleclock, to discard small backward counter steps.  (Larger steps are
00110 // assumed to be complete resyncs, which shouldn't happen.  If they do, a full
00111 // reinitialization of the outer algorithm should occur.)
00112 static int64_t GetCurrentTimeNanosFromKernel(uint64_t last_cycleclock,
00113                                              uint64_t *cycleclock) {
00114   // We try to read clock values at about the same time as the kernel clock.
00115   // This value gets adjusted up or down as estimate of how long that should
00116   // take, so we can reject attempts that take unusually long.
00117   static std::atomic<uint64_t> approx_syscall_time_in_cycles{10 * 1000};
00118 
00119   uint64_t local_approx_syscall_time_in_cycles =  // local copy
00120       approx_syscall_time_in_cycles.load(std::memory_order_relaxed);
00121 
00122   int64_t current_time_nanos_from_system;
00123   uint64_t before_cycles;
00124   uint64_t after_cycles;
00125   uint64_t elapsed_cycles;
00126   int loops = 0;
00127   do {
00128     before_cycles = GET_CURRENT_TIME_NANOS_CYCLECLOCK_NOW();
00129     current_time_nanos_from_system = GET_CURRENT_TIME_NANOS_FROM_SYSTEM();
00130     after_cycles = GET_CURRENT_TIME_NANOS_CYCLECLOCK_NOW();
00131     // elapsed_cycles is unsigned, so is large on overflow
00132     elapsed_cycles = after_cycles - before_cycles;
00133     if (elapsed_cycles >= local_approx_syscall_time_in_cycles &&
00134         ++loops == 20) {  // clock changed frequencies?  Back off.
00135       loops = 0;
00136       if (local_approx_syscall_time_in_cycles < 1000 * 1000) {
00137         local_approx_syscall_time_in_cycles =
00138             (local_approx_syscall_time_in_cycles + 1) << 1;
00139       }
00140       approx_syscall_time_in_cycles.store(
00141           local_approx_syscall_time_in_cycles,
00142           std::memory_order_relaxed);
00143     }
00144   } while (elapsed_cycles >= local_approx_syscall_time_in_cycles ||
00145            last_cycleclock - after_cycles < (static_cast<uint64_t>(1) << 16));
00146 
00147   // Number of times in a row we've seen a kernel time call take substantially
00148   // less than approx_syscall_time_in_cycles.
00149   static std::atomic<uint32_t> seen_smaller{ 0 };
00150 
00151   // Adjust approx_syscall_time_in_cycles to be within a factor of 2
00152   // of the typical time to execute one iteration of the loop above.
00153   if ((local_approx_syscall_time_in_cycles >> 1) < elapsed_cycles) {
00154     // measured time is no smaller than half current approximation
00155     seen_smaller.store(0, std::memory_order_relaxed);
00156   } else if (seen_smaller.fetch_add(1, std::memory_order_relaxed) >= 3) {
00157     // smaller delays several times in a row; reduce approximation by 12.5%
00158     const uint64_t new_approximation =
00159         local_approx_syscall_time_in_cycles -
00160         (local_approx_syscall_time_in_cycles >> 3);
00161     approx_syscall_time_in_cycles.store(new_approximation,
00162                                         std::memory_order_relaxed);
00163     seen_smaller.store(0, std::memory_order_relaxed);
00164   }
00165 
00166   *cycleclock = after_cycles;
00167   return current_time_nanos_from_system;
00168 }
00169 
00170 
00171 // ---------------------------------------------------------------------
00172 // An implementation of reader-write locks that use no atomic ops in the read
00173 // case.  This is a generalization of Lamport's method for reading a multiword
00174 // clock.  Increment a word on each write acquisition, using the low-order bit
00175 // as a spinlock; the word is the high word of the "clock".  Readers read the
00176 // high word, then all other data, then the high word again, and repeat the
00177 // read if the reads of the high words yields different answers, or an odd
00178 // value (either case suggests possible interference from a writer).
00179 // Here we use a spinlock to ensure only one writer at a time, rather than
00180 // spinning on the bottom bit of the word to benefit from SpinLock
00181 // spin-delay tuning.
00182 
00183 // Acquire seqlock (*seq) and return the value to be written to unlock.
00184 static inline uint64_t SeqAcquire(std::atomic<uint64_t> *seq) {
00185   uint64_t x = seq->fetch_add(1, std::memory_order_relaxed);
00186 
00187   // We put a release fence between update to *seq and writes to shared data.
00188   // Thus all stores to shared data are effectively release operations and
00189   // update to *seq above cannot be re-ordered past any of them.  Note that
00190   // this barrier is not for the fetch_add above.  A release barrier for the
00191   // fetch_add would be before it, not after.
00192   std::atomic_thread_fence(std::memory_order_release);
00193 
00194   return x + 2;   // original word plus 2
00195 }
00196 
00197 // Release seqlock (*seq) by writing x to it---a value previously returned by
00198 // SeqAcquire.
00199 static inline void SeqRelease(std::atomic<uint64_t> *seq, uint64_t x) {
00200   // The unlock store to *seq must have release ordering so that all
00201   // updates to shared data must finish before this store.
00202   seq->store(x, std::memory_order_release);  // release lock for readers
00203 }
00204 
00205 // ---------------------------------------------------------------------
00206 
00207 // "nsscaled" is unit of time equal to a (2**kScale)th of a nanosecond.
00208 enum { kScale = 30 };
00209 
00210 // The minimum interval between samples of the time base.
00211 // We pick enough time to amortize the cost of the sample,
00212 // to get a reasonably accurate cycle counter rate reading,
00213 // and not so much that calculations will overflow 64-bits.
00214 static const uint64_t kMinNSBetweenSamples = 2000 << 20;
00215 
00216 // We require that kMinNSBetweenSamples shifted by kScale
00217 // have at least a bit left over for 64-bit calculations.
00218 static_assert(((kMinNSBetweenSamples << (kScale + 1)) >> (kScale + 1)) ==
00219                kMinNSBetweenSamples,
00220                "cannot represent kMaxBetweenSamplesNSScaled");
00221 
00222 // A reader-writer lock protecting the static locations below.
00223 // See SeqAcquire() and SeqRelease() above.
00224 static absl::base_internal::SpinLock lock(
00225     absl::base_internal::kLinkerInitialized);
00226 static std::atomic<uint64_t> seq(0);
00227 
00228 // data from a sample of the kernel's time value
00229 struct TimeSampleAtomic {
00230   std::atomic<uint64_t> raw_ns;              // raw kernel time
00231   std::atomic<uint64_t> base_ns;             // our estimate of time
00232   std::atomic<uint64_t> base_cycles;         // cycle counter reading
00233   std::atomic<uint64_t> nsscaled_per_cycle;  // cycle period
00234   // cycles before we'll sample again (a scaled reciprocal of the period,
00235   // to avoid a division on the fast path).
00236   std::atomic<uint64_t> min_cycles_per_sample;
00237 };
00238 // Same again, but with non-atomic types
00239 struct TimeSample {
00240   uint64_t raw_ns;                 // raw kernel time
00241   uint64_t base_ns;                // our estimate of time
00242   uint64_t base_cycles;            // cycle counter reading
00243   uint64_t nsscaled_per_cycle;     // cycle period
00244   uint64_t min_cycles_per_sample;  // approx cycles before next sample
00245 };
00246 
00247 static struct TimeSampleAtomic last_sample;   // the last sample; under seq
00248 
00249 static int64_t GetCurrentTimeNanosSlowPath() ABSL_ATTRIBUTE_COLD;
00250 
00251 // Read the contents of *atomic into *sample.
00252 // Each field is read atomically, but to maintain atomicity between fields,
00253 // the access must be done under a lock.
00254 static void ReadTimeSampleAtomic(const struct TimeSampleAtomic *atomic,
00255                                  struct TimeSample *sample) {
00256   sample->base_ns = atomic->base_ns.load(std::memory_order_relaxed);
00257   sample->base_cycles = atomic->base_cycles.load(std::memory_order_relaxed);
00258   sample->nsscaled_per_cycle =
00259       atomic->nsscaled_per_cycle.load(std::memory_order_relaxed);
00260   sample->min_cycles_per_sample =
00261       atomic->min_cycles_per_sample.load(std::memory_order_relaxed);
00262   sample->raw_ns = atomic->raw_ns.load(std::memory_order_relaxed);
00263 }
00264 
00265 // Public routine.
00266 // Algorithm:  We wish to compute real time from a cycle counter.  In normal
00267 // operation, we construct a piecewise linear approximation to the kernel time
00268 // source, using the cycle counter value.  The start of each line segment is at
00269 // the same point as the end of the last, but may have a different slope (that
00270 // is, a different idea of the cycle counter frequency).  Every couple of
00271 // seconds, the kernel time source is sampled and compared with the current
00272 // approximation.  A new slope is chosen that, if followed for another couple
00273 // of seconds, will correct the error at the current position.  The information
00274 // for a sample is in the "last_sample" struct.  The linear approximation is
00275 //   estimated_time = last_sample.base_ns +
00276 //     last_sample.ns_per_cycle * (counter_reading - last_sample.base_cycles)
00277 // (ns_per_cycle is actually stored in different units and scaled, to avoid
00278 // overflow).  The base_ns of the next linear approximation is the
00279 // estimated_time using the last approximation; the base_cycles is the cycle
00280 // counter value at that time; the ns_per_cycle is the number of ns per cycle
00281 // measured since the last sample, but adjusted so that most of the difference
00282 // between the estimated_time and the kernel time will be corrected by the
00283 // estimated time to the next sample.  In normal operation, this algorithm
00284 // relies on:
00285 // - the cycle counter and kernel time rates not changing a lot in a few
00286 //   seconds.
00287 // - the client calling into the code often compared to a couple of seconds, so
00288 //   the time to the next correction can be estimated.
00289 // Any time ns_per_cycle is not known, a major error is detected, or the
00290 // assumption about frequent calls is violated, the implementation returns the
00291 // kernel time.  It records sufficient data that a linear approximation can
00292 // resume a little later.
00293 
00294 int64_t GetCurrentTimeNanos() {
00295   // read the data from the "last_sample" struct (but don't need raw_ns yet)
00296   // The reads of "seq" and test of the values emulate a reader lock.
00297   uint64_t base_ns;
00298   uint64_t base_cycles;
00299   uint64_t nsscaled_per_cycle;
00300   uint64_t min_cycles_per_sample;
00301   uint64_t seq_read0;
00302   uint64_t seq_read1;
00303 
00304   // If we have enough information to interpolate, the value returned will be
00305   // derived from this cycleclock-derived time estimate.  On some platforms
00306   // (POWER) the function to retrieve this value has enough complexity to
00307   // contribute to register pressure - reading it early before initializing
00308   // the other pieces of the calculation minimizes spill/restore instructions,
00309   // minimizing icache cost.
00310   uint64_t now_cycles = GET_CURRENT_TIME_NANOS_CYCLECLOCK_NOW();
00311 
00312   // Acquire pairs with the barrier in SeqRelease - if this load sees that
00313   // store, the shared-data reads necessarily see that SeqRelease's updates
00314   // to the same shared data.
00315   seq_read0 = seq.load(std::memory_order_acquire);
00316 
00317   base_ns = last_sample.base_ns.load(std::memory_order_relaxed);
00318   base_cycles = last_sample.base_cycles.load(std::memory_order_relaxed);
00319   nsscaled_per_cycle =
00320       last_sample.nsscaled_per_cycle.load(std::memory_order_relaxed);
00321   min_cycles_per_sample =
00322       last_sample.min_cycles_per_sample.load(std::memory_order_relaxed);
00323 
00324   // This acquire fence pairs with the release fence in SeqAcquire.  Since it
00325   // is sequenced between reads of shared data and seq_read1, the reads of
00326   // shared data are effectively acquiring.
00327   std::atomic_thread_fence(std::memory_order_acquire);
00328 
00329   // The shared-data reads are effectively acquire ordered, and the
00330   // shared-data writes are effectively release ordered. Therefore if our
00331   // shared-data reads see any of a particular update's shared-data writes,
00332   // seq_read1 is guaranteed to see that update's SeqAcquire.
00333   seq_read1 = seq.load(std::memory_order_relaxed);
00334 
00335   // Fast path.  Return if min_cycles_per_sample has not yet elapsed since the
00336   // last sample, and we read a consistent sample.  The fast path activates
00337   // only when min_cycles_per_sample is non-zero, which happens when we get an
00338   // estimate for the cycle time.  The predicate will fail if now_cycles <
00339   // base_cycles, or if some other thread is in the slow path.
00340   //
00341   // Since we now read now_cycles before base_ns, it is possible for now_cycles
00342   // to be less than base_cycles (if we were interrupted between those loads and
00343   // last_sample was updated). This is harmless, because delta_cycles will wrap
00344   // and report a time much much bigger than min_cycles_per_sample. In that case
00345   // we will take the slow path.
00346   uint64_t delta_cycles = now_cycles - base_cycles;
00347   if (seq_read0 == seq_read1 && (seq_read0 & 1) == 0 &&
00348       delta_cycles < min_cycles_per_sample) {
00349     return base_ns + ((delta_cycles * nsscaled_per_cycle) >> kScale);
00350   }
00351   return GetCurrentTimeNanosSlowPath();
00352 }
00353 
00354 // Return (a << kScale)/b.
00355 // Zero is returned if b==0.   Scaling is performed internally to
00356 // preserve precision without overflow.
00357 static uint64_t SafeDivideAndScale(uint64_t a, uint64_t b) {
00358   // Find maximum safe_shift so that
00359   //  0 <= safe_shift <= kScale  and  (a << safe_shift) does not overflow.
00360   int safe_shift = kScale;
00361   while (((a << safe_shift) >> safe_shift) != a) {
00362     safe_shift--;
00363   }
00364   uint64_t scaled_b = b >> (kScale - safe_shift);
00365   uint64_t quotient = 0;
00366   if (scaled_b != 0) {
00367     quotient = (a << safe_shift) / scaled_b;
00368   }
00369   return quotient;
00370 }
00371 
00372 static uint64_t UpdateLastSample(
00373     uint64_t now_cycles, uint64_t now_ns, uint64_t delta_cycles,
00374     const struct TimeSample *sample) ABSL_ATTRIBUTE_COLD;
00375 
00376 // The slow path of GetCurrentTimeNanos().  This is taken while gathering
00377 // initial samples, when enough time has elapsed since the last sample, and if
00378 // any other thread is writing to last_sample.
00379 //
00380 // Manually mark this 'noinline' to minimize stack frame size of the fast
00381 // path.  Without this, sometimes a compiler may inline this big block of code
00382 // into the fast path.  That causes lots of register spills and reloads that
00383 // are unnecessary unless the slow path is taken.
00384 //
00385 // TODO(absl-team): Remove this attribute when our compiler is smart enough
00386 // to do the right thing.
00387 ABSL_ATTRIBUTE_NOINLINE
00388 static int64_t GetCurrentTimeNanosSlowPath() LOCKS_EXCLUDED(lock) {
00389   // Serialize access to slow-path.  Fast-path readers are not blocked yet, and
00390   // code below must not modify last_sample until the seqlock is acquired.
00391   lock.Lock();
00392 
00393   // Sample the kernel time base.  This is the definition of
00394   // "now" if we take the slow path.
00395   static uint64_t last_now_cycles;  // protected by lock
00396   uint64_t now_cycles;
00397   uint64_t now_ns = GetCurrentTimeNanosFromKernel(last_now_cycles, &now_cycles);
00398   last_now_cycles = now_cycles;
00399 
00400   uint64_t estimated_base_ns;
00401 
00402   // ----------
00403   // Read the "last_sample" values again; this time holding the write lock.
00404   struct TimeSample sample;
00405   ReadTimeSampleAtomic(&last_sample, &sample);
00406 
00407   // ----------
00408   // Try running the fast path again; another thread may have updated the
00409   // sample between our run of the fast path and the sample we just read.
00410   uint64_t delta_cycles = now_cycles - sample.base_cycles;
00411   if (delta_cycles < sample.min_cycles_per_sample) {
00412     // Another thread updated the sample.  This path does not take the seqlock
00413     // so that blocked readers can make progress without blocking new readers.
00414     estimated_base_ns = sample.base_ns +
00415         ((delta_cycles * sample.nsscaled_per_cycle) >> kScale);
00416     stats_fast_slow_paths++;
00417   } else {
00418     estimated_base_ns =
00419         UpdateLastSample(now_cycles, now_ns, delta_cycles, &sample);
00420   }
00421 
00422   lock.Unlock();
00423 
00424   return estimated_base_ns;
00425 }
00426 
00427 // Main part of the algorithm.  Locks out readers, updates the approximation
00428 // using the new sample from the kernel, and stores the result in last_sample
00429 // for readers.  Returns the new estimated time.
00430 static uint64_t UpdateLastSample(uint64_t now_cycles, uint64_t now_ns,
00431                                  uint64_t delta_cycles,
00432                                  const struct TimeSample *sample)
00433     EXCLUSIVE_LOCKS_REQUIRED(lock) {
00434   uint64_t estimated_base_ns = now_ns;
00435   uint64_t lock_value = SeqAcquire(&seq);  // acquire seqlock to block readers
00436 
00437   // The 5s in the next if-statement limits the time for which we will trust
00438   // the cycle counter and our last sample to give a reasonable result.
00439   // Errors in the rate of the source clock can be multiplied by the ratio
00440   // between this limit and kMinNSBetweenSamples.
00441   if (sample->raw_ns == 0 ||  // no recent sample, or clock went backwards
00442       sample->raw_ns + static_cast<uint64_t>(5) * 1000 * 1000 * 1000 < now_ns ||
00443       now_ns < sample->raw_ns || now_cycles < sample->base_cycles) {
00444     // record this sample, and forget any previously known slope.
00445     last_sample.raw_ns.store(now_ns, std::memory_order_relaxed);
00446     last_sample.base_ns.store(estimated_base_ns, std::memory_order_relaxed);
00447     last_sample.base_cycles.store(now_cycles, std::memory_order_relaxed);
00448     last_sample.nsscaled_per_cycle.store(0, std::memory_order_relaxed);
00449     last_sample.min_cycles_per_sample.store(0, std::memory_order_relaxed);
00450     stats_initializations++;
00451   } else if (sample->raw_ns + 500 * 1000 * 1000 < now_ns &&
00452              sample->base_cycles + 100 < now_cycles) {
00453     // Enough time has passed to compute the cycle time.
00454     if (sample->nsscaled_per_cycle != 0) {  // Have a cycle time estimate.
00455       // Compute time from counter reading, but avoiding overflow
00456       // delta_cycles may be larger than on the fast path.
00457       uint64_t estimated_scaled_ns;
00458       int s = -1;
00459       do {
00460         s++;
00461         estimated_scaled_ns = (delta_cycles >> s) * sample->nsscaled_per_cycle;
00462       } while (estimated_scaled_ns / sample->nsscaled_per_cycle !=
00463                (delta_cycles >> s));
00464       estimated_base_ns = sample->base_ns +
00465                           (estimated_scaled_ns >> (kScale - s));
00466     }
00467 
00468     // Compute the assumed cycle time kMinNSBetweenSamples ns into the future
00469     // assuming the cycle counter rate stays the same as the last interval.
00470     uint64_t ns = now_ns - sample->raw_ns;
00471     uint64_t measured_nsscaled_per_cycle = SafeDivideAndScale(ns, delta_cycles);
00472 
00473     uint64_t assumed_next_sample_delta_cycles =
00474         SafeDivideAndScale(kMinNSBetweenSamples, measured_nsscaled_per_cycle);
00475 
00476     int64_t diff_ns = now_ns - estimated_base_ns;  // estimate low by this much
00477 
00478     // We want to set nsscaled_per_cycle so that our estimate of the ns time
00479     // at the assumed cycle time is the assumed ns time.
00480     // That is, we want to set nsscaled_per_cycle so:
00481     //  kMinNSBetweenSamples + diff_ns  ==
00482     //  (assumed_next_sample_delta_cycles * nsscaled_per_cycle) >> kScale
00483     // But we wish to damp oscillations, so instead correct only most
00484     // of our current error, by solving:
00485     //  kMinNSBetweenSamples + diff_ns - (diff_ns / 16) ==
00486     //  (assumed_next_sample_delta_cycles * nsscaled_per_cycle) >> kScale
00487     ns = kMinNSBetweenSamples + diff_ns - (diff_ns / 16);
00488     uint64_t new_nsscaled_per_cycle =
00489         SafeDivideAndScale(ns, assumed_next_sample_delta_cycles);
00490     if (new_nsscaled_per_cycle != 0 &&
00491         diff_ns < 100 * 1000 * 1000 && -diff_ns < 100 * 1000 * 1000) {
00492       // record the cycle time measurement
00493       last_sample.nsscaled_per_cycle.store(
00494           new_nsscaled_per_cycle, std::memory_order_relaxed);
00495       uint64_t new_min_cycles_per_sample =
00496           SafeDivideAndScale(kMinNSBetweenSamples, new_nsscaled_per_cycle);
00497       last_sample.min_cycles_per_sample.store(
00498           new_min_cycles_per_sample, std::memory_order_relaxed);
00499       stats_calibrations++;
00500     } else {  // something went wrong; forget the slope
00501       last_sample.nsscaled_per_cycle.store(0, std::memory_order_relaxed);
00502       last_sample.min_cycles_per_sample.store(0, std::memory_order_relaxed);
00503       estimated_base_ns = now_ns;
00504       stats_reinitializations++;
00505     }
00506     last_sample.raw_ns.store(now_ns, std::memory_order_relaxed);
00507     last_sample.base_ns.store(estimated_base_ns, std::memory_order_relaxed);
00508     last_sample.base_cycles.store(now_cycles, std::memory_order_relaxed);
00509   } else {
00510     // have a sample, but no slope; waiting for enough time for a calibration
00511     stats_slow_paths++;
00512   }
00513 
00514   SeqRelease(&seq, lock_value);  // release the readers
00515 
00516   return estimated_base_ns;
00517 }
00518 }  // namespace absl
00519 #endif  // ABSL_USE_CYCLECLOCK_FOR_GET_CURRENT_TIME_NANOS
00520 
00521 namespace absl {
00522 namespace {
00523 
00524 // Returns the maximum duration that SleepOnce() can sleep for.
00525 constexpr absl::Duration MaxSleep() {
00526 #ifdef _WIN32
00527   // Windows Sleep() takes unsigned long argument in milliseconds.
00528   return absl::Milliseconds(
00529       std::numeric_limits<unsigned long>::max());  // NOLINT(runtime/int)
00530 #else
00531   return absl::Seconds(std::numeric_limits<time_t>::max());
00532 #endif
00533 }
00534 
00535 // Sleeps for the given duration.
00536 // REQUIRES: to_sleep <= MaxSleep().
00537 void SleepOnce(absl::Duration to_sleep) {
00538 #ifdef _WIN32
00539   Sleep(to_sleep / absl::Milliseconds(1));
00540 #else
00541   struct timespec sleep_time = absl::ToTimespec(to_sleep);
00542   while (nanosleep(&sleep_time, &sleep_time) != 0 && errno == EINTR) {
00543     // Ignore signals and wait for the full interval to elapse.
00544   }
00545 #endif
00546 }
00547 
00548 }  // namespace
00549 }  // namespace absl
00550 
00551 extern "C" {
00552 
00553 ABSL_ATTRIBUTE_WEAK void AbslInternalSleepFor(absl::Duration duration) {
00554   while (duration > absl::ZeroDuration()) {
00555     absl::Duration to_sleep = std::min(duration, absl::MaxSleep());
00556     absl::SleepOnce(to_sleep);
00557     duration -= to_sleep;
00558   }
00559 }
00560 
00561 }  // extern "C"


abseil_cpp
Author(s):
autogenerated on Wed Jun 19 2019 19:42:14