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