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