1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 // Time represents an absolute point in coordinated universal time (UTC),
6 // internally represented as microseconds (s/1,000,000) since the Windows epoch
7 // (1601-01-01 00:00:00 UTC). System-dependent clock interface routines are
8 // defined in time_PLATFORM.cc. Note that values for Time may skew and jump
9 // around as the operating system makes adjustments to synchronize (e.g., with
10 // NTP servers). Thus, client code that uses the Time class must account for
11 // this.
12 //
13 // TimeDelta represents a duration of time, internally represented in
14 // microseconds.
15 //
16 // TimeTicks and ThreadTicks represent an abstract time that is most of the time
17 // incrementing, for use in measuring time durations. Internally, they are
18 // represented in microseconds. They cannot be converted to a human-readable
19 // time, but are guaranteed not to decrease (unlike the Time class). Note that
20 // TimeTicks may "stand still" (e.g., if the computer is suspended), and
21 // ThreadTicks will "stand still" whenever the thread has been de-scheduled by
22 // the operating system.
23 //
24 // All time classes are copyable, assignable, and occupy 64-bits per instance.
25 // As a result, prefer passing them by value:
26 //   void MyFunction(TimeDelta arg);
27 // If circumstances require, you may also pass by const reference:
28 //   void MyFunction(const TimeDelta& arg);  // Not preferred.
29 //
30 // Definitions of operator<< are provided to make these types work with
31 // DCHECK_EQ() and other log macros. For human-readable formatting, see
32 // "base/i18n/time_formatting.h".
33 //
34 // So many choices!  Which time class should you use?  Examples:
35 //
36 //   Time:        Interpreting the wall-clock time provided by a remote system.
37 //                Detecting whether cached resources have expired. Providing the
38 //                user with a display of the current date and time. Determining
39 //                the amount of time between events across re-boots of the
40 //                machine.
41 //
42 //   TimeTicks:   Tracking the amount of time a task runs. Executing delayed
43 //                tasks at the right time. Computing presentation timestamps.
44 //                Synchronizing audio and video using TimeTicks as a common
45 //                reference clock (lip-sync). Measuring network round-trip
46 //                latency.
47 //
48 //   ThreadTicks: Benchmarking how long the current thread has been doing actual
49 //                work.
50 
51 #ifndef BASE_TIME_TIME_H_
52 #define BASE_TIME_TIME_H_
53 
54 #include <stdint.h>
55 #include <time.h>
56 
57 #include <iosfwd>
58 #include <limits>
59 
60 #include "base/base_export.h"
61 #include "base/check_op.h"
62 #include "base/compiler_specific.h"
63 #include "base/numerics/safe_math.h"
64 #include "base/optional.h"
65 #include "base/strings/string_piece.h"
66 #include "build/build_config.h"
67 
68 #if defined(OS_FUCHSIA)
69 #include <zircon/types.h>
70 #endif
71 
72 #if defined(OS_APPLE)
73 #include <CoreFoundation/CoreFoundation.h>
74 // Avoid Mac system header macro leak.
75 #undef TYPE_BOOL
76 #endif
77 
78 #if defined(OS_ANDROID)
79 #include <jni.h>
80 #endif
81 
82 #if defined(OS_POSIX) || defined(OS_FUCHSIA)
83 #include <unistd.h>
84 #include <sys/time.h>
85 #endif
86 
87 #if defined(OS_WIN)
88 #include "base/gtest_prod_util.h"
89 #include "base/win/windows_types.h"
90 
91 namespace ABI {
92 namespace Windows {
93 namespace Foundation {
94 struct DateTime;
95 }  // namespace Foundation
96 }  // namespace Windows
97 }  // namespace ABI
98 #endif
99 
100 namespace base {
101 
102 class PlatformThreadHandle;
103 
104 // TimeDelta ------------------------------------------------------------------
105 
106 class BASE_EXPORT TimeDelta {
107  public:
108   constexpr TimeDelta() = default;
109 
110   // Converts units of time to TimeDeltas.
111   // These conversions treat minimum argument values as min type values or -inf,
112   // and maximum ones as max type values or +inf; and their results will produce
113   // an is_min() or is_max() TimeDelta. WARNING: Floating point arithmetic is
114   // such that FromXXXD(t.InXXXF()) may not precisely equal |t|. Hence, floating
115   // point values should not be used for storage.
116   static constexpr TimeDelta FromDays(int days);
117   static constexpr TimeDelta FromHours(int hours);
118   static constexpr TimeDelta FromMinutes(int minutes);
119   static constexpr TimeDelta FromSecondsD(double secs);
120   static constexpr TimeDelta FromSeconds(int64_t secs);
121   static constexpr TimeDelta FromMillisecondsD(double ms);
122   static constexpr TimeDelta FromMilliseconds(int64_t ms);
123   static constexpr TimeDelta FromMicrosecondsD(double us);
124   static constexpr TimeDelta FromMicroseconds(int64_t us);
125   static constexpr TimeDelta FromNanosecondsD(double ns);
126   static constexpr TimeDelta FromNanoseconds(int64_t ns);
127 
128 #if defined(OS_WIN)
129   static TimeDelta FromQPCValue(LONGLONG qpc_value);
130   // TODO(crbug.com/989694): Avoid base::TimeDelta factory functions
131   // based on absolute time
132   static TimeDelta FromFileTime(FILETIME ft);
133   static TimeDelta FromWinrtDateTime(ABI::Windows::Foundation::DateTime dt);
134 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
135   static TimeDelta FromTimeSpec(const timespec& ts);
136 #endif
137 #if defined(OS_FUCHSIA)
138   static TimeDelta FromZxDuration(zx_duration_t nanos);
139 #endif
140 #if defined(OS_MAC)
141   static TimeDelta FromMachTime(uint64_t mach_time);
142 #endif  // defined(OS_MAC)
143 
144   // Converts a frequency in Hertz (cycles per second) into a period.
145   static constexpr TimeDelta FromHz(double frequency);
146 
147   // From Go's doc at https://golang.org/pkg/time/#ParseDuration
148   //   [ParseDuration] parses a duration string. A duration string is
149   //   a possibly signed sequence of decimal numbers, each with optional
150   //   fraction and a unit suffix, such as "300ms", "-1.5h" or "2h45m".
151   //   Valid time units are "ns", "us" "ms", "s", "m", "h".
152   //
153   // Special values that are allowed without specifying units:
154   //  "0", "+0", "-0" -> TimeDelta()
155   //  "inf", "+inf"   -> TimeDelta::Max()
156   //  "-inf"          -> TimeDelta::Min()
157   // Returns |base::nullopt| when parsing fails. Numbers larger than 2^63-1
158   // will fail parsing. Overflowing `number * unit` will return +/-inf, as
159   // appropriate.
160   static Optional<TimeDelta> FromString(StringPiece duration_string);
161 
162   // Converts an integer value representing TimeDelta to a class. This is used
163   // when deserializing a |TimeDelta| structure, using a value known to be
164   // compatible. It is not provided as a constructor because the integer type
165   // may be unclear from the perspective of a caller.
166   //
167   // DEPRECATED - Do not use in new code. http://crbug.com/634507
FromInternalValue(int64_t delta)168   static constexpr TimeDelta FromInternalValue(int64_t delta) {
169     return TimeDelta(delta);
170   }
171 
172   // Returns the maximum time delta, which should be greater than any reasonable
173   // time delta we might compare it to. Adding or subtracting the maximum time
174   // delta to a time or another time delta has an undefined result.
175   static constexpr TimeDelta Max();
176 
177   // Returns the minimum time delta, which should be less than than any
178   // reasonable time delta we might compare it to. Adding or subtracting the
179   // minimum time delta to a time or another time delta has an undefined result.
180   static constexpr TimeDelta Min();
181 
182   // Returns the internal numeric value of the TimeDelta object. Please don't
183   // use this and do arithmetic on it, as it is more error prone than using the
184   // provided operators.
185   // For serializing, use FromInternalValue to reconstitute.
186   //
187   // DEPRECATED - Do not use in new code. http://crbug.com/634507
ToInternalValue()188   constexpr int64_t ToInternalValue() const { return delta_; }
189 
190   // Returns the magnitude (absolute value) of this TimeDelta.
magnitude()191   constexpr TimeDelta magnitude() const {
192     // The code below will not work correctly in this corner case.
193     if (is_min())
194       return Max();
195 
196     // std::abs() is not currently constexpr.  The following is a simple
197     // branchless implementation:
198     const int64_t mask = delta_ >> (sizeof(delta_) * 8 - 1);
199     return TimeDelta((delta_ + mask) ^ mask);
200   }
201 
202   // Returns true if the time delta is zero.
is_zero()203   constexpr bool is_zero() const { return delta_ == 0; }
204 
205   // Returns true if the time delta is the maximum/minimum time delta.
is_max()206   constexpr bool is_max() const { return *this == Max(); }
is_min()207   constexpr bool is_min() const { return *this == Min(); }
is_inf()208   constexpr bool is_inf() const { return is_min() || is_max(); }
209 
210 #if defined(OS_POSIX) || defined(OS_FUCHSIA)
211   struct timespec ToTimeSpec() const;
212 #endif
213 #if defined(OS_FUCHSIA)
214   zx_duration_t ToZxDuration() const;
215 #endif
216 #if defined(OS_WIN)
217   ABI::Windows::Foundation::DateTime ToWinrtDateTime() const;
218 #endif
219 
220   // Returns the frequency in Hertz (cycles per second) that has a period of
221   // *this.
ToHz()222   constexpr double ToHz() const { return FromSeconds(1) / *this; }
223 
224   // Returns the time delta in some unit. Minimum argument values return as
225   // -inf for doubles and min type values otherwise. Maximum ones are treated as
226   // +inf for doubles and max type values otherwise. Their results will produce
227   // an is_min() or is_max() TimeDelta. The InXYZF versions return a floating
228   // point value. The InXYZ versions return a truncated value (aka rounded
229   // towards zero, std::trunc() behavior). The InXYZFloored() versions round to
230   // lesser integers (std::floor() behavior). The XYZRoundedUp() versions round
231   // up to greater integers (std::ceil() behavior). WARNING: Floating point
232   // arithmetic is such that FromXXXD(t.InXXXF()) may not precisely equal |t|.
233   // Hence, floating point values should not be used for storage.
234   int InDays() const;
235   int InDaysFloored() const;
236   constexpr int InHours() const;
237   constexpr int InMinutes() const;
238   double InSecondsF() const;
239   int64_t InSeconds() const;
240   double InMillisecondsF() const;
241   int64_t InMilliseconds() const;
242   int64_t InMillisecondsRoundedUp() const;
InMicroseconds()243   constexpr int64_t InMicroseconds() const { return delta_; }
244   double InMicrosecondsF() const;
245   constexpr int64_t InNanoseconds() const;
246 
247   // Computations with other deltas.
248   constexpr TimeDelta operator+(TimeDelta other) const;
249   constexpr TimeDelta operator-(TimeDelta other) const;
250 
251   constexpr TimeDelta& operator+=(TimeDelta other) {
252     return *this = (*this + other);
253   }
254   constexpr TimeDelta& operator-=(TimeDelta other) {
255     return *this = (*this - other);
256   }
257   constexpr TimeDelta operator-() const {
258     if (!is_inf())
259       return TimeDelta(-delta_);
260     return (delta_ < 0) ? Max() : Min();
261   }
262 
263   // Computations with numeric types.
264   template <typename T>
265   constexpr TimeDelta operator*(T a) const {
266     CheckedNumeric<int64_t> rv(delta_);
267     rv *= a;
268     if (rv.IsValid())
269       return TimeDelta(rv.ValueOrDie());
270     return ((delta_ < 0) == (a < 0)) ? Max() : Min();
271   }
272   template <typename T>
273   constexpr TimeDelta operator/(T a) const {
274     CheckedNumeric<int64_t> rv(delta_);
275     rv /= a;
276     if (rv.IsValid())
277       return TimeDelta(rv.ValueOrDie());
278     return ((delta_ < 0) == (a < 0)) ? Max() : Min();
279   }
280   template <typename T>
281   constexpr TimeDelta& operator*=(T a) {
282     return *this = (*this * a);
283   }
284   template <typename T>
285   constexpr TimeDelta& operator/=(T a) {
286     return *this = (*this / a);
287   }
288 
289   // This does floating-point division. For an integer result, either call
290   // IntDiv(), or (possibly clearer) use this operator with
291   // base::Clamp{Ceil,Floor,Round}() or base::saturated_cast() (for truncation).
292   // Note that converting to double here drops precision to 53 bits.
293   constexpr double operator/(TimeDelta a) const {
294     // 0/0 and inf/inf (any combination of positive and negative) are invalid
295     // (they are almost certainly not intentional, and result in NaN, which
296     // turns into 0 if clamped to an integer; this makes introducing subtle bugs
297     // too easy).
298     CHECK(!is_zero() || !a.is_zero());
299     CHECK(!is_inf() || !a.is_inf());
300 
301     return ToDouble() / a.ToDouble();
302   }
IntDiv(TimeDelta a)303   constexpr int64_t IntDiv(TimeDelta a) const {
304     if (!is_inf() && !a.is_zero())
305       return delta_ / a.delta_;
306 
307     // For consistency, use the same edge case CHECKs and behavior as the code
308     // above.
309     CHECK(!is_zero() || !a.is_zero());
310     CHECK(!is_inf() || !a.is_inf());
311     return ((delta_ < 0) == (a.delta_ < 0))
312                ? std::numeric_limits<int64_t>::max()
313                : std::numeric_limits<int64_t>::min();
314   }
315 
316   constexpr TimeDelta operator%(TimeDelta a) const {
317     return TimeDelta(
318         (is_inf() || a.is_zero() || a.is_inf()) ? delta_ : (delta_ % a.delta_));
319   }
320   TimeDelta& operator%=(TimeDelta other) { return *this = (*this % other); }
321 
322   // Comparison operators.
323   constexpr bool operator==(TimeDelta other) const {
324     return delta_ == other.delta_;
325   }
326   constexpr bool operator!=(TimeDelta other) const {
327     return delta_ != other.delta_;
328   }
329   constexpr bool operator<(TimeDelta other) const {
330     return delta_ < other.delta_;
331   }
332   constexpr bool operator<=(TimeDelta other) const {
333     return delta_ <= other.delta_;
334   }
335   constexpr bool operator>(TimeDelta other) const {
336     return delta_ > other.delta_;
337   }
338   constexpr bool operator>=(TimeDelta other) const {
339     return delta_ >= other.delta_;
340   }
341 
342   // Returns this delta, ceiled/floored/rounded-away-from-zero to the nearest
343   // multiple of |interval|.
344   TimeDelta CeilToMultiple(TimeDelta interval) const;
345   TimeDelta FloorToMultiple(TimeDelta interval) const;
346   TimeDelta RoundToMultiple(TimeDelta interval) const;
347 
348  private:
349   // Constructs a delta given the duration in microseconds. This is private
350   // to avoid confusion by callers with an integer constructor. Use
351   // FromSeconds, FromMilliseconds, etc. instead.
TimeDelta(int64_t delta_us)352   constexpr explicit TimeDelta(int64_t delta_us) : delta_(delta_us) {}
353 
354   // Returns a double representation of this TimeDelta's tick count.  In
355   // particular, Max()/Min() are converted to +/-infinity.
ToDouble()356   constexpr double ToDouble() const {
357     if (!is_inf())
358       return static_cast<double>(delta_);
359     return (delta_ < 0) ? -std::numeric_limits<double>::infinity()
360                         : std::numeric_limits<double>::infinity();
361   }
362 
363   // Delta in microseconds.
364   int64_t delta_ = 0;
365 };
366 
367 constexpr TimeDelta TimeDelta::operator+(TimeDelta other) const {
368   if (!other.is_inf())
369     return TimeDelta(int64_t{base::ClampAdd(delta_, other.delta_)});
370 
371   // Additions involving two infinities are only valid if signs match.
372   CHECK(!is_inf() || (delta_ == other.delta_));
373   return other;
374 }
375 
376 constexpr TimeDelta TimeDelta::operator-(TimeDelta other) const {
377   if (!other.is_inf())
378     return TimeDelta(int64_t{base::ClampSub(delta_, other.delta_)});
379 
380   // Subtractions involving two infinities are only valid if signs differ.
381   CHECK_NE(delta_, other.delta_);
382   return (other.delta_ < 0) ? Max() : Min();
383 }
384 
385 template <typename T>
386 constexpr TimeDelta operator*(T a, TimeDelta td) {
387   return td * a;
388 }
389 
390 // For logging use only.
391 BASE_EXPORT std::ostream& operator<<(std::ostream& os, TimeDelta time_delta);
392 
393 // TimeBase--------------------------------------------------------------------
394 
395 // Do not reference the time_internal::TimeBase template class directly.  Please
396 // use one of the time subclasses instead, and only reference the public
397 // TimeBase members via those classes.
398 namespace time_internal {
399 
400 // Provides value storage and comparison/math operations common to all time
401 // classes. Each subclass provides for strong type-checking to ensure
402 // semantically meaningful comparison/math of time values from the same clock
403 // source or timeline.
404 template<class TimeClass>
405 class TimeBase {
406  public:
407   static constexpr int64_t kHoursPerDay = 24;
408   static constexpr int64_t kSecondsPerMinute = 60;
409   static constexpr int64_t kMinutesPerHour = 60;
410   static constexpr int64_t kSecondsPerHour =
411       kSecondsPerMinute * kMinutesPerHour;
412   static constexpr int64_t kMillisecondsPerSecond = 1000;
413   static constexpr int64_t kMillisecondsPerDay =
414       kMillisecondsPerSecond * kSecondsPerHour * kHoursPerDay;
415   static constexpr int64_t kMicrosecondsPerMillisecond = 1000;
416   static constexpr int64_t kMicrosecondsPerSecond =
417       kMicrosecondsPerMillisecond * kMillisecondsPerSecond;
418   static constexpr int64_t kMicrosecondsPerMinute =
419       kMicrosecondsPerSecond * kSecondsPerMinute;
420   static constexpr int64_t kMicrosecondsPerHour =
421       kMicrosecondsPerMinute * kMinutesPerHour;
422   static constexpr int64_t kMicrosecondsPerDay =
423       kMicrosecondsPerHour * kHoursPerDay;
424   static constexpr int64_t kMicrosecondsPerWeek = kMicrosecondsPerDay * 7;
425   static constexpr int64_t kNanosecondsPerMicrosecond = 1000;
426   static constexpr int64_t kNanosecondsPerSecond =
427       kNanosecondsPerMicrosecond * kMicrosecondsPerSecond;
428 
429   // Returns true if this object has not been initialized.
430   //
431   // Warning: Be careful when writing code that performs math on time values,
432   // since it's possible to produce a valid "zero" result that should not be
433   // interpreted as a "null" value.
is_null()434   constexpr bool is_null() const { return us_ == 0; }
435 
436   // Returns true if this object represents the maximum/minimum time.
is_max()437   constexpr bool is_max() const { return *this == Max(); }
is_min()438   constexpr bool is_min() const { return *this == Min(); }
is_inf()439   constexpr bool is_inf() const { return is_min() || is_max(); }
440 
441   // Returns the maximum/minimum times, which should be greater/less than than
442   // any reasonable time with which we might compare it.
Max()443   static constexpr TimeClass Max() {
444     return TimeClass(std::numeric_limits<int64_t>::max());
445   }
446 
Min()447   static constexpr TimeClass Min() {
448     return TimeClass(std::numeric_limits<int64_t>::min());
449   }
450 
451   // For serializing only. Use FromInternalValue() to reconstitute. Please don't
452   // use this and do arithmetic on it, as it is more error prone than using the
453   // provided operators.
454   //
455   // DEPRECATED - Do not use in new code. For serializing Time values, prefer
456   // Time::ToDeltaSinceWindowsEpoch().InMicroseconds(). http://crbug.com/634507
ToInternalValue()457   constexpr int64_t ToInternalValue() const { return us_; }
458 
459   // The amount of time since the origin (or "zero") point. This is a syntactic
460   // convenience to aid in code readability, mainly for debugging/testing use
461   // cases.
462   //
463   // Warning: While the Time subclass has a fixed origin point, the origin for
464   // the other subclasses can vary each time the application is restarted.
since_origin()465   constexpr TimeDelta since_origin() const {
466     return TimeDelta::FromMicroseconds(us_);
467   }
468 
469   constexpr TimeClass& operator=(TimeClass other) {
470     us_ = other.us_;
471     return *(static_cast<TimeClass*>(this));
472   }
473 
474   // Compute the difference between two times.
475   constexpr TimeDelta operator-(TimeClass other) const {
476     return TimeDelta::FromMicroseconds(us_ - other.us_);
477   }
478 
479   // Return a new time modified by some delta.
480   constexpr TimeClass operator+(TimeDelta delta) const {
481     return TimeClass(
482         (TimeDelta::FromMicroseconds(us_) + delta).InMicroseconds());
483   }
484   constexpr TimeClass operator-(TimeDelta delta) const {
485     return TimeClass(
486         (TimeDelta::FromMicroseconds(us_) - delta).InMicroseconds());
487   }
488 
489   // Modify by some time delta.
490   constexpr TimeClass& operator+=(TimeDelta delta) {
491     return static_cast<TimeClass&>(*this = (*this + delta));
492   }
493   constexpr TimeClass& operator-=(TimeDelta delta) {
494     return static_cast<TimeClass&>(*this = (*this - delta));
495   }
496 
497   // Comparison operators
498   constexpr bool operator==(TimeClass other) const { return us_ == other.us_; }
499   constexpr bool operator!=(TimeClass other) const { return us_ != other.us_; }
500   constexpr bool operator<(TimeClass other) const { return us_ < other.us_; }
501   constexpr bool operator<=(TimeClass other) const { return us_ <= other.us_; }
502   constexpr bool operator>(TimeClass other) const { return us_ > other.us_; }
503   constexpr bool operator>=(TimeClass other) const { return us_ >= other.us_; }
504 
505  protected:
TimeBase(int64_t us)506   constexpr explicit TimeBase(int64_t us) : us_(us) {}
507 
508   // Time value in a microsecond timebase.
509   int64_t us_;
510 };
511 
512 }  // namespace time_internal
513 
514 template <class TimeClass>
515 inline constexpr TimeClass operator+(TimeDelta delta, TimeClass t) {
516   return t + delta;
517 }
518 
519 // Time -----------------------------------------------------------------------
520 
521 // Represents a wall clock time in UTC. Values are not guaranteed to be
522 // monotonically non-decreasing and are subject to large amounts of skew.
523 // Time is stored internally as microseconds since the Windows epoch (1601).
524 class BASE_EXPORT Time : public time_internal::TimeBase<Time> {
525  public:
526   // Offset of UNIX epoch (1970-01-01 00:00:00 UTC) from Windows FILETIME epoch
527   // (1601-01-01 00:00:00 UTC), in microseconds. This value is derived from the
528   // following: ((1970-1601)*365+89)*24*60*60*1000*1000, where 89 is the number
529   // of leap year days between 1601 and 1970: (1970-1601)/4 excluding 1700,
530   // 1800, and 1900.
531   static constexpr int64_t kTimeTToMicrosecondsOffset =
532       INT64_C(11644473600000000);
533 
534 #if defined(OS_WIN)
535   // To avoid overflow in QPC to Microseconds calculations, since we multiply
536   // by kMicrosecondsPerSecond, then the QPC value should not exceed
537   // (2^63 - 1) / 1E6. If it exceeds that threshold, we divide then multiply.
538   static constexpr int64_t kQPCOverflowThreshold = INT64_C(0x8637BD05AF7);
539 #endif
540 
541 // kExplodedMinYear and kExplodedMaxYear define the platform-specific limits
542 // for values passed to FromUTCExploded() and FromLocalExploded(). Those
543 // functions will return false if passed values outside these limits. The limits
544 // are inclusive, meaning that the API should support all dates within a given
545 // limit year.
546 //
547 // WARNING: These are not the same limits for the inverse functionality,
548 // UTCExplode() and LocalExplode(). See method comments for further details.
549 #if defined(OS_WIN)
550   static constexpr int kExplodedMinYear = 1601;
551   static constexpr int kExplodedMaxYear = 30827;
552 #elif defined(OS_IOS) && !__LP64__
553   static constexpr int kExplodedMinYear = std::numeric_limits<int>::min();
554   static constexpr int kExplodedMaxYear = std::numeric_limits<int>::max();
555 #elif defined(OS_APPLE)
556   static constexpr int kExplodedMinYear = 1902;
557   static constexpr int kExplodedMaxYear = std::numeric_limits<int>::max();
558 #elif defined(OS_ANDROID)
559   // Though we use 64-bit time APIs on both 32 and 64 bit Android, some OS
560   // versions like KitKat (ARM but not x86 emulator) can't handle some early
561   // dates (e.g. before 1170). So we set min conservatively here.
562   static constexpr int kExplodedMinYear = 1902;
563   static constexpr int kExplodedMaxYear = std::numeric_limits<int>::max();
564 #else
565   static constexpr int kExplodedMinYear =
566       (sizeof(time_t) == 4 ? 1902 : std::numeric_limits<int>::min());
567   static constexpr int kExplodedMaxYear =
568       (sizeof(time_t) == 4 ? 2037 : std::numeric_limits<int>::max());
569 #endif
570 
571   // Represents an exploded time that can be formatted nicely. This is kind of
572   // like the Win32 SYSTEMTIME structure or the Unix "struct tm" with a few
573   // additions and changes to prevent errors.
574   struct BASE_EXPORT Exploded {
575     int year;          // Four digit year "2007"
576     int month;         // 1-based month (values 1 = January, etc.)
577     int day_of_week;   // 0-based day of week (0 = Sunday, etc.)
578     int day_of_month;  // 1-based day of month (1-31)
579     int hour;          // Hour within the current day (0-23)
580     int minute;        // Minute within the current hour (0-59)
581     int second;        // Second within the current minute (0-59 plus leap
582                        //   seconds which may take it up to 60).
583     int millisecond;   // Milliseconds within the current second (0-999)
584 
585     // A cursory test for whether the data members are within their
586     // respective ranges. A 'true' return value does not guarantee the
587     // Exploded value can be successfully converted to a Time value.
588     bool HasValidValues() const;
589   };
590 
591   // Contains the NULL time. Use Time::Now() to get the current time.
Time()592   constexpr Time() : TimeBase(0) {}
593 
594   // Returns the time for epoch in Unix-like system (Jan 1, 1970).
595   static Time UnixEpoch();
596 
597   // Returns the current time. Watch out, the system might adjust its clock
598   // in which case time will actually go backwards. We don't guarantee that
599   // times are increasing, or that two calls to Now() won't be the same.
600   static Time Now();
601 
602   // Returns the current time. Same as Now() except that this function always
603   // uses system time so that there are no discrepancies between the returned
604   // time and system time even on virtual environments including our test bot.
605   // For timing sensitive unittests, this function should be used.
606   static Time NowFromSystemTime();
607 
608   // Converts to/from TimeDeltas relative to the Windows epoch (1601-01-01
609   // 00:00:00 UTC). Prefer these methods for opaque serialization and
610   // deserialization of time values, e.g.
611   //
612   //   // Serialization:
613   //   base::Time last_updated = ...;
614   //   SaveToDatabase(last_updated.ToDeltaSinceWindowsEpoch().InMicroseconds());
615   //
616   //   // Deserialization:
617   //   base::Time last_updated = base::Time::FromDeltaSinceWindowsEpoch(
618   //       base::TimeDelta::FromMicroseconds(LoadFromDatabase()));
619   static Time FromDeltaSinceWindowsEpoch(TimeDelta delta);
620   TimeDelta ToDeltaSinceWindowsEpoch() const;
621 
622   // Converts to/from time_t in UTC and a Time class.
623   static Time FromTimeT(time_t tt);
624   time_t ToTimeT() const;
625 
626   // Converts time to/from a double which is the number of seconds since epoch
627   // (Jan 1, 1970).  Webkit uses this format to represent time.
628   // Because WebKit initializes double time value to 0 to indicate "not
629   // initialized", we map it to empty Time object that also means "not
630   // initialized".
631   static Time FromDoubleT(double dt);
632   double ToDoubleT() const;
633 
634 #if defined(OS_POSIX) || defined(OS_FUCHSIA)
635   // Converts the timespec structure to time. MacOS X 10.8.3 (and tentatively,
636   // earlier versions) will have the |ts|'s tv_nsec component zeroed out,
637   // having a 1 second resolution, which agrees with
638   // https://developer.apple.com/legacy/library/#technotes/tn/tn1150.html#HFSPlusDates.
639   static Time FromTimeSpec(const timespec& ts);
640 #endif
641 
642   // Converts to/from the Javascript convention for times, a number of
643   // milliseconds since the epoch:
644   // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getTime.
645   //
646   // Don't use ToJsTime() in new code, since it contains a subtle hack (only
647   // exactly 1601-01-01 00:00 UTC is represented as 1970-01-01 00:00 UTC), and
648   // that is not appropriate for general use. Try to use ToJsTimeIgnoringNull()
649   // unless you have a very good reason to use ToJsTime().
650   static Time FromJsTime(double ms_since_epoch);
651   double ToJsTime() const;
652   double ToJsTimeIgnoringNull() const;
653 
654   // Converts to/from Java convention for times, a number of milliseconds since
655   // the epoch. Because the Java format has less resolution, converting to Java
656   // time is a lossy operation.
657   static Time FromJavaTime(int64_t ms_since_epoch);
658   int64_t ToJavaTime() const;
659 
660 #if defined(OS_POSIX) || defined(OS_FUCHSIA)
661   static Time FromTimeVal(struct timeval t);
662   struct timeval ToTimeVal() const;
663 #endif
664 
665 #if defined(OS_FUCHSIA)
666   static Time FromZxTime(zx_time_t time);
667   zx_time_t ToZxTime() const;
668 #endif
669 
670 #if defined(OS_APPLE)
671   static Time FromCFAbsoluteTime(CFAbsoluteTime t);
672   CFAbsoluteTime ToCFAbsoluteTime() const;
673 #endif
674 
675 #if defined(OS_DRAGONFLY)
676   static const int kMinLowResolutionThresholdMs = 20;
677 #elif defined(OS_WIN)
678   static Time FromFileTime(FILETIME ft);
679   FILETIME ToFileTime() const;
680 
681   // The minimum time of a low resolution timer.  This is basically a windows
682   // constant of ~15.6ms.  While it does vary on some older OS versions, we'll
683   // treat it as static across all windows versions.
684   static const int kMinLowResolutionThresholdMs = 16;
685 
686   // Enable or disable Windows high resolution timer.
687   static void EnableHighResolutionTimer(bool enable);
688 
689   // Activates or deactivates the high resolution timer based on the |activate|
690   // flag.  If the HighResolutionTimer is not Enabled (see
691   // EnableHighResolutionTimer), this function will return false.  Otherwise
692   // returns true.  Each successful activate call must be paired with a
693   // subsequent deactivate call.
694   // All callers to activate the high resolution timer must eventually call
695   // this function to deactivate the high resolution timer.
696   static bool ActivateHighResolutionTimer(bool activate);
697 
698   // Returns true if the high resolution timer is both enabled and activated.
699   // This is provided for testing only, and is not tracked in a thread-safe
700   // way.
701   static bool IsHighResolutionTimerInUse();
702 
703   // The following two functions are used to report the fraction of elapsed time
704   // that the high resolution timer is activated.
705   // ResetHighResolutionTimerUsage() resets the cumulative usage and starts the
706   // measurement interval and GetHighResolutionTimerUsage() returns the
707   // percentage of time since the reset that the high resolution timer was
708   // activated.
709   // ResetHighResolutionTimerUsage() must be called at least once before calling
710   // GetHighResolutionTimerUsage(); otherwise the usage result would be
711   // undefined.
712   static void ResetHighResolutionTimerUsage();
713   static double GetHighResolutionTimerUsage();
714 #endif  // defined(OS_WIN)
715 
716   // Converts an exploded structure representing either the local time or UTC
717   // into a Time class. Returns false on a failure when, for example, a day of
718   // month is set to 31 on a 28-30 day month. Returns Time(0) on overflow.
FromUTCExploded(const Exploded & exploded,Time * time)719   static bool FromUTCExploded(const Exploded& exploded,
720                               Time* time) WARN_UNUSED_RESULT {
721     return FromExploded(false, exploded, time);
722   }
FromLocalExploded(const Exploded & exploded,Time * time)723   static bool FromLocalExploded(const Exploded& exploded,
724                                 Time* time) WARN_UNUSED_RESULT {
725     return FromExploded(true, exploded, time);
726   }
727 
728   // Converts a string representation of time to a Time object.
729   // An example of a time string which is converted is as below:-
730   // "Tue, 15 Nov 1994 12:45:26 GMT". If the timezone is not specified
731   // in the input string, FromString assumes local time and FromUTCString
732   // assumes UTC. A timezone that cannot be parsed (e.g. "UTC" which is not
733   // specified in RFC822) is treated as if the timezone is not specified.
734   //
735   // WARNING: the underlying converter is very permissive. For example: it is
736   // not checked whether a given day of the week matches the date; Feb 29
737   // silently becomes Mar 1 in non-leap years; under certain conditions, whole
738   // English sentences may be parsed successfully and yield unexpected results.
739   //
740   // TODO(iyengar) Move the FromString/FromTimeT/ToTimeT/FromFileTime to
741   // a new time converter class.
FromString(const char * time_string,Time * parsed_time)742   static bool FromString(const char* time_string,
743                          Time* parsed_time) WARN_UNUSED_RESULT {
744     return FromStringInternal(time_string, true, parsed_time);
745   }
FromUTCString(const char * time_string,Time * parsed_time)746   static bool FromUTCString(const char* time_string,
747                             Time* parsed_time) WARN_UNUSED_RESULT {
748     return FromStringInternal(time_string, false, parsed_time);
749   }
750 
751   // Fills the given |exploded| structure with either the local time or UTC from
752   // this Time instance. If the conversion cannot be made, the output will be
753   // assigned invalid values. Use Exploded::HasValidValues() to confirm a
754   // successful conversion.
755   //
756   // Y10K compliance: This method will successfully convert all Times that
757   // represent dates on/after the start of the year 1601 and on/before the start
758   // of the year 30828. Some platforms might convert over a wider input range.
UTCExplode(Exploded * exploded)759   void UTCExplode(Exploded* exploded) const { Explode(false, exploded); }
LocalExplode(Exploded * exploded)760   void LocalExplode(Exploded* exploded) const { Explode(true, exploded); }
761 
762   // The following two functions round down the time to the nearest day in
763   // either UTC or local time. It will represent midnight on that day.
UTCMidnight()764   Time UTCMidnight() const { return Midnight(false); }
LocalMidnight()765   Time LocalMidnight() const { return Midnight(true); }
766 
767   // Converts an integer value representing Time to a class. This may be used
768   // when deserializing a |Time| structure, using a value known to be
769   // compatible. It is not provided as a constructor because the integer type
770   // may be unclear from the perspective of a caller.
771   //
772   // DEPRECATED - Do not use in new code. For deserializing Time values, prefer
773   // Time::FromDeltaSinceWindowsEpoch(). http://crbug.com/634507
FromInternalValue(int64_t us)774   static constexpr Time FromInternalValue(int64_t us) { return Time(us); }
775 
776  private:
777   friend class time_internal::TimeBase<Time>;
778 
Time(int64_t microseconds_since_win_epoch)779   constexpr explicit Time(int64_t microseconds_since_win_epoch)
780       : TimeBase(microseconds_since_win_epoch) {}
781 
782   // Explodes the given time to either local time |is_local = true| or UTC
783   // |is_local = false|.
784   void Explode(bool is_local, Exploded* exploded) const;
785 
786   // Unexplodes a given time assuming the source is either local time
787   // |is_local = true| or UTC |is_local = false|. Function returns false on
788   // failure and sets |time| to Time(0). Otherwise returns true and sets |time|
789   // to non-exploded time.
790   static bool FromExploded(bool is_local,
791                            const Exploded& exploded,
792                            Time* time) WARN_UNUSED_RESULT;
793 
794   // Some platforms use the ICU library to provide To/FromExploded, when their
795   // native library implementations are insufficient in some way.
796   static void ExplodeUsingIcu(int64_t millis_since_unix_epoch,
797                               bool is_local,
798                               Exploded* exploded);
799   static bool FromExplodedUsingIcu(bool is_local,
800                                    const Exploded& exploded,
801                                    int64_t* millis_since_unix_epoch)
802       WARN_UNUSED_RESULT;
803 
804   // Rounds down the time to the nearest day in either local time
805   // |is_local = true| or UTC |is_local = false|.
806   Time Midnight(bool is_local) const;
807 
808   // Converts a string representation of time to a Time object.
809   // An example of a time string which is converted is as below:-
810   // "Tue, 15 Nov 1994 12:45:26 GMT". If the timezone is not specified
811   // in the input string, local time |is_local = true| or
812   // UTC |is_local = false| is assumed. A timezone that cannot be parsed
813   // (e.g. "UTC" which is not specified in RFC822) is treated as if the
814   // timezone is not specified.
815   static bool FromStringInternal(const char* time_string,
816                                  bool is_local,
817                                  Time* parsed_time) WARN_UNUSED_RESULT;
818 
819   // Comparison does not consider |day_of_week| when doing the operation.
820   static bool ExplodedMostlyEquals(const Exploded& lhs,
821                                    const Exploded& rhs) WARN_UNUSED_RESULT;
822 
823   // Converts the provided time in milliseconds since the Unix epoch (1970) to a
824   // Time object, avoiding overflows.
825   static bool FromMillisecondsSinceUnixEpoch(int64_t unix_milliseconds,
826                                              Time* time) WARN_UNUSED_RESULT;
827 
828   // Returns the milliseconds since the Unix epoch (1970), rounding the
829   // microseconds towards -infinity.
830   int64_t ToRoundedDownMillisecondsSinceUnixEpoch() const;
831 };
832 
833 // TimeDelta functions that must appear below the declarations of Time/TimeDelta
834 
835 // static
FromDays(int days)836 constexpr TimeDelta TimeDelta::FromDays(int days) {
837   return (days == std::numeric_limits<int>::max())
838              ? Max()
839              : TimeDelta(days * Time::kMicrosecondsPerDay);
840 }
841 
842 // static
FromHours(int hours)843 constexpr TimeDelta TimeDelta::FromHours(int hours) {
844   return (hours == std::numeric_limits<int>::max())
845              ? Max()
846              : TimeDelta(hours * Time::kMicrosecondsPerHour);
847 }
848 
849 // static
FromMinutes(int minutes)850 constexpr TimeDelta TimeDelta::FromMinutes(int minutes) {
851   return (minutes == std::numeric_limits<int>::max())
852              ? Max()
853              : TimeDelta(minutes * Time::kMicrosecondsPerMinute);
854 }
855 
856 // static
FromSecondsD(double secs)857 constexpr TimeDelta TimeDelta::FromSecondsD(double secs) {
858   return TimeDelta(
859       saturated_cast<int64_t>(secs * Time::kMicrosecondsPerSecond));
860 }
861 
862 // static
FromSeconds(int64_t secs)863 constexpr TimeDelta TimeDelta::FromSeconds(int64_t secs) {
864   return TimeDelta(int64_t{base::ClampMul(secs, Time::kMicrosecondsPerSecond)});
865 }
866 
867 // static
FromMillisecondsD(double ms)868 constexpr TimeDelta TimeDelta::FromMillisecondsD(double ms) {
869   return TimeDelta(
870       saturated_cast<int64_t>(ms * Time::kMicrosecondsPerMillisecond));
871 }
872 
873 // static
FromMilliseconds(int64_t ms)874 constexpr TimeDelta TimeDelta::FromMilliseconds(int64_t ms) {
875   return TimeDelta(
876       int64_t{base::ClampMul(ms, Time::kMicrosecondsPerMillisecond)});
877 }
878 
879 // static
FromMicrosecondsD(double us)880 constexpr TimeDelta TimeDelta::FromMicrosecondsD(double us) {
881   return TimeDelta(saturated_cast<int64_t>(us));
882 }
883 
884 // static
FromMicroseconds(int64_t us)885 constexpr TimeDelta TimeDelta::FromMicroseconds(int64_t us) {
886   return TimeDelta(us);
887 }
888 
889 // static
FromNanosecondsD(double ns)890 constexpr TimeDelta TimeDelta::FromNanosecondsD(double ns) {
891   return TimeDelta(
892       saturated_cast<int64_t>(ns / Time::kNanosecondsPerMicrosecond));
893 }
894 
895 // static
FromNanoseconds(int64_t ns)896 constexpr TimeDelta TimeDelta::FromNanoseconds(int64_t ns) {
897   return TimeDelta(ns / Time::kNanosecondsPerMicrosecond);
898 }
899 
900 // static
FromHz(double frequency)901 constexpr TimeDelta TimeDelta::FromHz(double frequency) {
902   return FromSeconds(1) / frequency;
903 }
904 
InHours()905 constexpr int TimeDelta::InHours() const {
906   // saturated_cast<> is necessary since very large (but still less than
907   // min/max) deltas would result in overflow.
908   return saturated_cast<int>(delta_ / Time::kMicrosecondsPerHour);
909 }
910 
InMinutes()911 constexpr int TimeDelta::InMinutes() const {
912   // saturated_cast<> is necessary since very large (but still less than
913   // min/max) deltas would result in overflow.
914   return saturated_cast<int>(delta_ / Time::kMicrosecondsPerMinute);
915 }
916 
InNanoseconds()917 constexpr int64_t TimeDelta::InNanoseconds() const {
918   return base::ClampMul(delta_, Time::kNanosecondsPerMicrosecond);
919 }
920 
921 // static
Max()922 constexpr TimeDelta TimeDelta::Max() {
923   return TimeDelta(std::numeric_limits<int64_t>::max());
924 }
925 
926 // static
Min()927 constexpr TimeDelta TimeDelta::Min() {
928   return TimeDelta(std::numeric_limits<int64_t>::min());
929 }
930 
931 // For logging use only.
932 BASE_EXPORT std::ostream& operator<<(std::ostream& os, Time time);
933 
934 // TimeTicks ------------------------------------------------------------------
935 
936 // Represents monotonically non-decreasing clock time.
937 class BASE_EXPORT TimeTicks : public time_internal::TimeBase<TimeTicks> {
938  public:
939   // The underlying clock used to generate new TimeTicks.
940   enum class Clock {
941     FUCHSIA_ZX_CLOCK_MONOTONIC,
942     LINUX_CLOCK_MONOTONIC,
943     IOS_CF_ABSOLUTE_TIME_MINUS_KERN_BOOTTIME,
944     MAC_MACH_ABSOLUTE_TIME,
945     WIN_QPC,
946     WIN_ROLLOVER_PROTECTED_TIME_GET_TIME
947   };
948 
TimeTicks()949   constexpr TimeTicks() : TimeBase(0) {}
950 
951   // Platform-dependent tick count representing "right now." When
952   // IsHighResolution() returns false, the resolution of the clock could be
953   // as coarse as ~15.6ms. Otherwise, the resolution should be no worse than one
954   // microsecond.
955   static TimeTicks Now();
956 
957   // Returns true if the high resolution clock is working on this system and
958   // Now() will return high resolution values. Note that, on systems where the
959   // high resolution clock works but is deemed inefficient, the low resolution
960   // clock will be used instead.
961   static bool IsHighResolution() WARN_UNUSED_RESULT;
962 
963   // Returns true if TimeTicks is consistent across processes, meaning that
964   // timestamps taken on different processes can be safely compared with one
965   // another. (Note that, even on platforms where this returns true, time values
966   // from different threads that are within one tick of each other must be
967   // considered to have an ambiguous ordering.)
968   static bool IsConsistentAcrossProcesses() WARN_UNUSED_RESULT;
969 
970 #if defined(OS_FUCHSIA)
971   // Converts between TimeTicks and an ZX_CLOCK_MONOTONIC zx_time_t value.
972   static TimeTicks FromZxTime(zx_time_t nanos_since_boot);
973   zx_time_t ToZxTime() const;
974 #endif
975 
976 #if defined(OS_WIN)
977   // Translates an absolute QPC timestamp into a TimeTicks value. The returned
978   // value has the same origin as Now(). Do NOT attempt to use this if
979   // IsHighResolution() returns false.
980   static TimeTicks FromQPCValue(LONGLONG qpc_value);
981 #endif
982 
983 #if defined(OS_MAC)
984   static TimeTicks FromMachAbsoluteTime(uint64_t mach_absolute_time);
985 #endif  // defined(OS_MAC)
986 
987 #if defined(OS_ANDROID) || defined(OS_CHROMEOS)
988   // Converts to TimeTicks the value obtained from SystemClock.uptimeMillis().
989   // Note: this convertion may be non-monotonic in relation to previously
990   // obtained TimeTicks::Now() values because of the truncation (to
991   // milliseconds) performed by uptimeMillis().
992   static TimeTicks FromUptimeMillis(int64_t uptime_millis_value);
993 #endif
994 
995   // Get an estimate of the TimeTick value at the time of the UnixEpoch. Because
996   // Time and TimeTicks respond differently to user-set time and NTP
997   // adjustments, this number is only an estimate. Nevertheless, this can be
998   // useful when you need to relate the value of TimeTicks to a real time and
999   // date. Note: Upon first invocation, this function takes a snapshot of the
1000   // realtime clock to establish a reference point.  This function will return
1001   // the same value for the duration of the application, but will be different
1002   // in future application runs.
1003   static TimeTicks UnixEpoch();
1004 
1005   // Returns |this| snapped to the next tick, given a |tick_phase| and
1006   // repeating |tick_interval| in both directions. |this| may be before,
1007   // after, or equal to the |tick_phase|.
1008   TimeTicks SnappedToNextTick(TimeTicks tick_phase,
1009                               TimeDelta tick_interval) const;
1010 
1011   // Returns an enum indicating the underlying clock being used to generate
1012   // TimeTicks timestamps. This function should only be used for debugging and
1013   // logging purposes.
1014   static Clock GetClock();
1015 
1016   // Converts an integer value representing TimeTicks to a class. This may be
1017   // used when deserializing a |TimeTicks| structure, using a value known to be
1018   // compatible. It is not provided as a constructor because the integer type
1019   // may be unclear from the perspective of a caller.
1020   //
1021   // DEPRECATED - Do not use in new code. For deserializing TimeTicks values,
1022   // prefer TimeTicks + TimeDelta(). http://crbug.com/634507
FromInternalValue(int64_t us)1023   static constexpr TimeTicks FromInternalValue(int64_t us) {
1024     return TimeTicks(us);
1025   }
1026 
1027  protected:
1028 #if defined(OS_WIN)
1029   typedef DWORD (*TickFunctionType)(void);
1030   static TickFunctionType SetMockTickFunction(TickFunctionType ticker);
1031 #endif
1032 
1033  private:
1034   friend class time_internal::TimeBase<TimeTicks>;
1035 
1036   // Please use Now() to create a new object. This is for internal use
1037   // and testing.
TimeTicks(int64_t us)1038   constexpr explicit TimeTicks(int64_t us) : TimeBase(us) {}
1039 };
1040 
1041 // For logging use only.
1042 BASE_EXPORT std::ostream& operator<<(std::ostream& os, TimeTicks time_ticks);
1043 
1044 // ThreadTicks ----------------------------------------------------------------
1045 
1046 // Represents a clock, specific to a particular thread, than runs only while the
1047 // thread is running.
1048 class BASE_EXPORT ThreadTicks : public time_internal::TimeBase<ThreadTicks> {
1049  public:
ThreadTicks()1050   constexpr ThreadTicks() : TimeBase(0) {}
1051 
1052   // Returns true if ThreadTicks::Now() is supported on this system.
IsSupported()1053   static bool IsSupported() WARN_UNUSED_RESULT {
1054 #if (defined(_POSIX_THREAD_CPUTIME) && (_POSIX_THREAD_CPUTIME >= 0)) || \
1055     defined(OS_MAC) || defined(OS_ANDROID) || defined(OS_FUCHSIA)
1056     return true;
1057 #elif defined(OS_WIN)
1058     return IsSupportedWin();
1059 #else
1060     return false;
1061 #endif
1062   }
1063 
1064   // Waits until the initialization is completed. Needs to be guarded with a
1065   // call to IsSupported().
WaitUntilInitialized()1066   static void WaitUntilInitialized() {
1067 #if defined(OS_WIN)
1068     WaitUntilInitializedWin();
1069 #endif
1070   }
1071 
1072   // Returns thread-specific CPU-time on systems that support this feature.
1073   // Needs to be guarded with a call to IsSupported(). Use this timer
1074   // to (approximately) measure how much time the calling thread spent doing
1075   // actual work vs. being de-scheduled. May return bogus results if the thread
1076   // migrates to another CPU between two calls. Returns an empty ThreadTicks
1077   // object until the initialization is completed. If a clock reading is
1078   // absolutely needed, call WaitUntilInitialized() before this method.
1079   static ThreadTicks Now();
1080 
1081 #if defined(OS_WIN)
1082   // Similar to Now() above except this returns thread-specific CPU time for an
1083   // arbitrary thread. All comments for Now() method above apply apply to this
1084   // method as well.
1085   static ThreadTicks GetForThread(const PlatformThreadHandle& thread_handle);
1086 #endif
1087 
1088   // Converts an integer value representing ThreadTicks to a class. This may be
1089   // used when deserializing a |ThreadTicks| structure, using a value known to
1090   // be compatible. It is not provided as a constructor because the integer type
1091   // may be unclear from the perspective of a caller.
1092   //
1093   // DEPRECATED - Do not use in new code. For deserializing ThreadTicks values,
1094   // prefer ThreadTicks + TimeDelta(). http://crbug.com/634507
FromInternalValue(int64_t us)1095   static constexpr ThreadTicks FromInternalValue(int64_t us) {
1096     return ThreadTicks(us);
1097   }
1098 
1099  private:
1100   friend class time_internal::TimeBase<ThreadTicks>;
1101 
1102   // Please use Now() or GetForThread() to create a new object. This is for
1103   // internal use and testing.
ThreadTicks(int64_t us)1104   constexpr explicit ThreadTicks(int64_t us) : TimeBase(us) {}
1105 
1106 #if defined(OS_WIN)
1107   FRIEND_TEST_ALL_PREFIXES(TimeTicks, TSCTicksPerSecond);
1108 
1109 #if defined(ARCH_CPU_ARM64)
1110   // TSCTicksPerSecond is not supported on Windows on Arm systems because the
1111   // cycle-counting methods use the actual CPU cycle count, and not a consistent
1112   // incrementing counter.
1113 #else
1114   // Returns the frequency of the TSC in ticks per second, or 0 if it hasn't
1115   // been measured yet. Needs to be guarded with a call to IsSupported().
1116   // This method is declared here rather than in the anonymous namespace to
1117   // allow testing.
1118   static double TSCTicksPerSecond();
1119 #endif
1120 
1121   static bool IsSupportedWin() WARN_UNUSED_RESULT;
1122   static void WaitUntilInitializedWin();
1123 #endif
1124 };
1125 
1126 // For logging use only.
1127 BASE_EXPORT std::ostream& operator<<(std::ostream& os, ThreadTicks time_ticks);
1128 
1129 }  // namespace base
1130 
1131 #endif  // BASE_TIME_TIME_H_
1132