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