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