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