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 can not 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
25 // instance. Thus, they can be efficiently passed by-value (as opposed to
26 // by-reference).
27 //
28 // Definitions of operator<< are provided to make these types work with
29 // DCHECK_EQ() and other log macros. For human-readable formatting, see
30 // "base/i18n/time_formatting.h".
31 //
32 // So many choices!  Which time class should you use?  Examples:
33 //
34 //   Time:        Interpreting the wall-clock time provided by a remote
35 //                system. Detecting whether cached resources have
36 //                expired. Providing the user with a display of the current date
37 //                and time. Determining the amount of time between events across
38 //                re-boots of the machine.
39 //
40 //   TimeTicks:   Tracking the amount of time a task runs. Executing delayed
41 //                tasks at the right time. Computing presentation timestamps.
42 //                Synchronizing audio and video using TimeTicks as a common
43 //                reference clock (lip-sync). Measuring network round-trip
44 //                latency.
45 //
46 //   ThreadTicks: Benchmarking how long the current thread has been doing actual
47 //                work.
48 
49 #ifndef BASE_TIME_TIME_H_
50 #define BASE_TIME_TIME_H_
51 
52 #include <stdint.h>
53 #include <time.h>
54 
55 #include <iosfwd>
56 #include <limits>
57 
58 #include "base/base_export.h"
59 #include "base/numerics/safe_math.h"
60 #include "build/build_config.h"
61 
62 #if defined(OS_MACOSX)
63 #include <CoreFoundation/CoreFoundation.h>
64 // Avoid Mac system header macro leak.
65 #undef TYPE_BOOL
66 #endif
67 
68 #if defined(OS_POSIX)
69 #include <unistd.h>
70 #include <sys/time.h>
71 #endif
72 
73 #if defined(OS_WIN)
74 // For FILETIME in FromFileTime, until it moves to a new converter class.
75 // See TODO(iyengar) below.
76 #include <windows.h>
77 
78 #include "base/gtest_prod_util.h"
79 #endif
80 
81 namespace base {
82 
83 class TimeDelta;
84 
85 // The functions in the time_internal namespace are meant to be used only by the
86 // time classes and functions.  Please use the math operators defined in the
87 // time classes instead.
88 namespace time_internal {
89 
90 // Add or subtract |value| from a TimeDelta. The int64_t argument and return
91 // value are in terms of a microsecond timebase.
92 BASE_EXPORT int64_t SaturatedAdd(TimeDelta delta, int64_t value);
93 BASE_EXPORT int64_t SaturatedSub(TimeDelta delta, int64_t value);
94 
95 // Clamp |value| on overflow and underflow conditions. The int64_t argument and
96 // return value are in terms of a microsecond timebase.
97 BASE_EXPORT int64_t FromCheckedNumeric(const CheckedNumeric<int64_t> value);
98 
99 }  // namespace time_internal
100 
101 // TimeDelta ------------------------------------------------------------------
102 
103 class BASE_EXPORT TimeDelta {
104  public:
TimeDelta()105   TimeDelta() : delta_(0) {
106   }
107 
108   // Converts units of time to TimeDeltas.
109   static TimeDelta FromDays(int days);
110   static TimeDelta FromHours(int hours);
111   static TimeDelta FromMinutes(int minutes);
112   static TimeDelta FromSeconds(int64_t secs);
113   static TimeDelta FromMilliseconds(int64_t ms);
114   static TimeDelta FromSecondsD(double secs);
115   static TimeDelta FromMillisecondsD(double ms);
116   static TimeDelta FromMicroseconds(int64_t us);
117 #if defined(OS_WIN)
118   static TimeDelta FromQPCValue(LONGLONG qpc_value);
119 #endif
120 
121   // Converts an integer value representing TimeDelta to a class. This is used
122   // when deserializing a |TimeDelta| structure, using a value known to be
123   // compatible. It is not provided as a constructor because the integer type
124   // may be unclear from the perspective of a caller.
FromInternalValue(int64_t delta)125   static TimeDelta FromInternalValue(int64_t delta) { return TimeDelta(delta); }
126 
127   // Returns the maximum time delta, which should be greater than any reasonable
128   // time delta we might compare it to. Adding or subtracting the maximum time
129   // delta to a time or another time delta has an undefined result.
130   static TimeDelta Max();
131 
132   // Returns the internal numeric value of the TimeDelta object. Please don't
133   // use this and do arithmetic on it, as it is more error prone than using the
134   // provided operators.
135   // For serializing, use FromInternalValue to reconstitute.
ToInternalValue()136   int64_t ToInternalValue() const { return delta_; }
137 
138   // Returns the magnitude (absolute value) of this TimeDelta.
magnitude()139   TimeDelta magnitude() const {
140     // Some toolchains provide an incomplete C++11 implementation and lack an
141     // int64_t overload for std::abs().  The following is a simple branchless
142     // implementation:
143     const int64_t mask = delta_ >> (sizeof(delta_) * 8 - 1);
144     return TimeDelta((delta_ + mask) ^ mask);
145   }
146 
147   // Returns true if the time delta is zero.
is_zero()148   bool is_zero() const {
149     return delta_ == 0;
150   }
151 
152   // Returns true if the time delta is the maximum time delta.
is_max()153   bool is_max() const { return delta_ == std::numeric_limits<int64_t>::max(); }
154 
155 #if defined(OS_POSIX)
156   struct timespec ToTimeSpec() const;
157 #endif
158 
159   // Returns the time delta in some unit. The F versions return a floating
160   // point value, the "regular" versions return a rounded-down value.
161   //
162   // InMillisecondsRoundedUp() instead returns an integer that is rounded up
163   // to the next full millisecond.
164   int InDays() const;
165   int InHours() const;
166   int InMinutes() const;
167   double InSecondsF() const;
168   int64_t InSeconds() const;
169   double InMillisecondsF() const;
170   int64_t InMilliseconds() const;
171   int64_t InMillisecondsRoundedUp() const;
172   int64_t InMicroseconds() const;
173 
174   TimeDelta& operator=(TimeDelta other) {
175     delta_ = other.delta_;
176     return *this;
177   }
178 
179   // Computations with other deltas.
180   TimeDelta operator+(TimeDelta other) const {
181     return TimeDelta(time_internal::SaturatedAdd(*this, other.delta_));
182   }
183   TimeDelta operator-(TimeDelta other) const {
184     return TimeDelta(time_internal::SaturatedSub(*this, other.delta_));
185   }
186 
187   TimeDelta& operator+=(TimeDelta other) {
188     return *this = (*this + other);
189   }
190   TimeDelta& operator-=(TimeDelta other) {
191     return *this = (*this - other);
192   }
193   TimeDelta operator-() const {
194     return TimeDelta(-delta_);
195   }
196 
197   // Computations with numeric types.
198   template<typename T>
199   TimeDelta operator*(T a) const {
200     CheckedNumeric<int64_t> rv(delta_);
201     rv *= a;
202     return TimeDelta(time_internal::FromCheckedNumeric(rv));
203   }
204   template<typename T>
205   TimeDelta operator/(T a) const {
206     CheckedNumeric<int64_t> rv(delta_);
207     rv /= a;
208     return TimeDelta(time_internal::FromCheckedNumeric(rv));
209   }
210   template<typename T>
211   TimeDelta& operator*=(T a) {
212     return *this = (*this * a);
213   }
214   template<typename T>
215   TimeDelta& operator/=(T a) {
216     return *this = (*this / a);
217   }
218 
219   int64_t operator/(TimeDelta a) const { return delta_ / a.delta_; }
220   TimeDelta operator%(TimeDelta a) const {
221     return TimeDelta(delta_ % a.delta_);
222   }
223 
224   // Comparison operators.
225   bool operator==(TimeDelta other) const {
226     return delta_ == other.delta_;
227   }
228   bool operator!=(TimeDelta other) const {
229     return delta_ != other.delta_;
230   }
231   bool operator<(TimeDelta other) const {
232     return delta_ < other.delta_;
233   }
234   bool operator<=(TimeDelta other) const {
235     return delta_ <= other.delta_;
236   }
237   bool operator>(TimeDelta other) const {
238     return delta_ > other.delta_;
239   }
240   bool operator>=(TimeDelta other) const {
241     return delta_ >= other.delta_;
242   }
243 
244  private:
245   friend int64_t time_internal::SaturatedAdd(TimeDelta delta, int64_t value);
246   friend int64_t time_internal::SaturatedSub(TimeDelta delta, int64_t value);
247 
248   // Constructs a delta given the duration in microseconds. This is private
249   // to avoid confusion by callers with an integer constructor. Use
250   // FromSeconds, FromMilliseconds, etc. instead.
TimeDelta(int64_t delta_us)251   explicit TimeDelta(int64_t delta_us) : delta_(delta_us) {}
252 
253   // Private method to build a delta from a double.
254   static TimeDelta FromDouble(double value);
255 
256   // Delta in microseconds.
257   int64_t delta_;
258 };
259 
260 template<typename T>
261 inline TimeDelta operator*(T a, TimeDelta td) {
262   return td * a;
263 }
264 
265 // For logging use only.
266 BASE_EXPORT std::ostream& operator<<(std::ostream& os, TimeDelta time_delta);
267 
268 // Do not reference the time_internal::TimeBase template class directly.  Please
269 // use one of the time subclasses instead, and only reference the public
270 // TimeBase members via those classes.
271 namespace time_internal {
272 
273 // TimeBase--------------------------------------------------------------------
274 
275 // Provides value storage and comparison/math operations common to all time
276 // classes. Each subclass provides for strong type-checking to ensure
277 // semantically meaningful comparison/math of time values from the same clock
278 // source or timeline.
279 template<class TimeClass>
280 class TimeBase {
281  public:
282   static const int64_t kHoursPerDay = 24;
283   static const int64_t kMillisecondsPerSecond = 1000;
284   static const int64_t kMillisecondsPerDay =
285       kMillisecondsPerSecond * 60 * 60 * kHoursPerDay;
286   static const int64_t kMicrosecondsPerMillisecond = 1000;
287   static const int64_t kMicrosecondsPerSecond =
288       kMicrosecondsPerMillisecond * kMillisecondsPerSecond;
289   static const int64_t kMicrosecondsPerMinute = kMicrosecondsPerSecond * 60;
290   static const int64_t kMicrosecondsPerHour = kMicrosecondsPerMinute * 60;
291   static const int64_t kMicrosecondsPerDay =
292       kMicrosecondsPerHour * kHoursPerDay;
293   static const int64_t kMicrosecondsPerWeek = kMicrosecondsPerDay * 7;
294   static const int64_t kNanosecondsPerMicrosecond = 1000;
295   static const int64_t kNanosecondsPerSecond =
296       kNanosecondsPerMicrosecond * kMicrosecondsPerSecond;
297 
298   // Returns true if this object has not been initialized.
299   //
300   // Warning: Be careful when writing code that performs math on time values,
301   // since it's possible to produce a valid "zero" result that should not be
302   // interpreted as a "null" value.
is_null()303   bool is_null() const {
304     return us_ == 0;
305   }
306 
307   // Returns true if this object represents the maximum time.
is_max()308   bool is_max() const { return us_ == std::numeric_limits<int64_t>::max(); }
309 
310   // For serializing only. Use FromInternalValue() to reconstitute. Please don't
311   // use this and do arithmetic on it, as it is more error prone than using the
312   // provided operators.
ToInternalValue()313   int64_t ToInternalValue() const { return us_; }
314 
315   TimeClass& operator=(TimeClass other) {
316     us_ = other.us_;
317     return *(static_cast<TimeClass*>(this));
318   }
319 
320   // Compute the difference between two times.
321   TimeDelta operator-(TimeClass other) const {
322     return TimeDelta::FromMicroseconds(us_ - other.us_);
323   }
324 
325   // Return a new time modified by some delta.
326   TimeClass operator+(TimeDelta delta) const {
327     return TimeClass(time_internal::SaturatedAdd(delta, us_));
328   }
329   TimeClass operator-(TimeDelta delta) const {
330     return TimeClass(-time_internal::SaturatedSub(delta, us_));
331   }
332 
333   // Modify by some time delta.
334   TimeClass& operator+=(TimeDelta delta) {
335     return static_cast<TimeClass&>(*this = (*this + delta));
336   }
337   TimeClass& operator-=(TimeDelta delta) {
338     return static_cast<TimeClass&>(*this = (*this - delta));
339   }
340 
341   // Comparison operators
342   bool operator==(TimeClass other) const {
343     return us_ == other.us_;
344   }
345   bool operator!=(TimeClass other) const {
346     return us_ != other.us_;
347   }
348   bool operator<(TimeClass other) const {
349     return us_ < other.us_;
350   }
351   bool operator<=(TimeClass other) const {
352     return us_ <= other.us_;
353   }
354   bool operator>(TimeClass other) const {
355     return us_ > other.us_;
356   }
357   bool operator>=(TimeClass other) const {
358     return us_ >= other.us_;
359   }
360 
361   // Converts an integer value representing TimeClass to a class. This is used
362   // when deserializing a |TimeClass| structure, using a value known to be
363   // compatible. It is not provided as a constructor because the integer type
364   // may be unclear from the perspective of a caller.
FromInternalValue(int64_t us)365   static TimeClass FromInternalValue(int64_t us) { return TimeClass(us); }
366 
367  protected:
TimeBase(int64_t us)368   explicit TimeBase(int64_t us) : us_(us) {}
369 
370   // Time value in a microsecond timebase.
371   int64_t us_;
372 };
373 
374 }  // namespace time_internal
375 
376 template<class TimeClass>
377 inline TimeClass operator+(TimeDelta delta, TimeClass t) {
378   return t + delta;
379 }
380 
381 // Time -----------------------------------------------------------------------
382 
383 // Represents a wall clock time in UTC. Values are not guaranteed to be
384 // monotonically non-decreasing and are subject to large amounts of skew.
385 class BASE_EXPORT Time : public time_internal::TimeBase<Time> {
386  public:
387   // The representation of Jan 1, 1970 UTC in microseconds since the
388   // platform-dependent epoch.
389   static const int64_t kTimeTToMicrosecondsOffset;
390 
391 #if !defined(OS_WIN)
392   // On Mac & Linux, this value is the delta from the Windows epoch of 1601 to
393   // the Posix delta of 1970. This is used for migrating between the old
394   // 1970-based epochs to the new 1601-based ones. It should be removed from
395   // this global header and put in the platform-specific ones when we remove the
396   // migration code.
397   static const int64_t kWindowsEpochDeltaMicroseconds;
398 #else
399   // To avoid overflow in QPC to Microseconds calculations, since we multiply
400   // by kMicrosecondsPerSecond, then the QPC value should not exceed
401   // (2^63 - 1) / 1E6. If it exceeds that threshold, we divide then multiply.
402   enum : int64_t{kQPCOverflowThreshold = 0x8637BD05AF7};
403 #endif
404 
405   // Represents an exploded time that can be formatted nicely. This is kind of
406   // like the Win32 SYSTEMTIME structure or the Unix "struct tm" with a few
407   // additions and changes to prevent errors.
408   struct BASE_EXPORT Exploded {
409     int year;          // Four digit year "2007"
410     int month;         // 1-based month (values 1 = January, etc.)
411     int day_of_week;   // 0-based day of week (0 = Sunday, etc.)
412     int day_of_month;  // 1-based day of month (1-31)
413     int hour;          // Hour within the current day (0-23)
414     int minute;        // Minute within the current hour (0-59)
415     int second;        // Second within the current minute (0-59 plus leap
416                        //   seconds which may take it up to 60).
417     int millisecond;   // Milliseconds within the current second (0-999)
418 
419     // A cursory test for whether the data members are within their
420     // respective ranges. A 'true' return value does not guarantee the
421     // Exploded value can be successfully converted to a Time value.
422     bool HasValidValues() const;
423   };
424 
425   // Contains the NULL time. Use Time::Now() to get the current time.
Time()426   Time() : TimeBase(0) {
427   }
428 
429   // Returns the time for epoch in Unix-like system (Jan 1, 1970).
430   static Time UnixEpoch();
431 
432   // Returns the current time. Watch out, the system might adjust its clock
433   // in which case time will actually go backwards. We don't guarantee that
434   // times are increasing, or that two calls to Now() won't be the same.
435   static Time Now();
436 
437   // Returns the maximum time, which should be greater than any reasonable time
438   // with which we might compare it.
439   static Time Max();
440 
441   // Returns the current time. Same as Now() except that this function always
442   // uses system time so that there are no discrepancies between the returned
443   // time and system time even on virtual environments including our test bot.
444   // For timing sensitive unittests, this function should be used.
445   static Time NowFromSystemTime();
446 
447   // Converts to/from time_t in UTC and a Time class.
448   // TODO(brettw) this should be removed once everybody starts using the |Time|
449   // class.
450   static Time FromTimeT(time_t tt);
451   time_t ToTimeT() const;
452 
453   // Converts time to/from a double which is the number of seconds since epoch
454   // (Jan 1, 1970).  Webkit uses this format to represent time.
455   // Because WebKit initializes double time value to 0 to indicate "not
456   // initialized", we map it to empty Time object that also means "not
457   // initialized".
458   static Time FromDoubleT(double dt);
459   double ToDoubleT() const;
460 
461 #if defined(OS_POSIX)
462   // Converts the timespec structure to time. MacOS X 10.8.3 (and tentatively,
463   // earlier versions) will have the |ts|'s tv_nsec component zeroed out,
464   // having a 1 second resolution, which agrees with
465   // https://developer.apple.com/legacy/library/#technotes/tn/tn1150.html#HFSPlusDates.
466   static Time FromTimeSpec(const timespec& ts);
467 #endif
468 
469   // Converts to/from the Javascript convention for times, a number of
470   // milliseconds since the epoch:
471   // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getTime.
472   static Time FromJsTime(double ms_since_epoch);
473   double ToJsTime() const;
474 
475   // Converts to Java convention for times, a number of
476   // milliseconds since the epoch.
477   int64_t ToJavaTime() const;
478 
479 #if defined(OS_POSIX)
480   static Time FromTimeVal(struct timeval t);
481   struct timeval ToTimeVal() const;
482 #endif
483 
484 #if defined(OS_MACOSX)
485   static Time FromCFAbsoluteTime(CFAbsoluteTime t);
486   CFAbsoluteTime ToCFAbsoluteTime() const;
487 #endif
488 
489 #if defined(OS_WIN)
490   static Time FromFileTime(FILETIME ft);
491   FILETIME ToFileTime() const;
492 
493   // The minimum time of a low resolution timer.  This is basically a windows
494   // constant of ~15.6ms.  While it does vary on some older OS versions, we'll
495   // treat it as static across all windows versions.
496   static const int kMinLowResolutionThresholdMs = 16;
497 
498   // Enable or disable Windows high resolution timer.
499   static void EnableHighResolutionTimer(bool enable);
500 
501   // Activates or deactivates the high resolution timer based on the |activate|
502   // flag.  If the HighResolutionTimer is not Enabled (see
503   // EnableHighResolutionTimer), this function will return false.  Otherwise
504   // returns true.  Each successful activate call must be paired with a
505   // subsequent deactivate call.
506   // All callers to activate the high resolution timer must eventually call
507   // this function to deactivate the high resolution timer.
508   static bool ActivateHighResolutionTimer(bool activate);
509 
510   // Returns true if the high resolution timer is both enabled and activated.
511   // This is provided for testing only, and is not tracked in a thread-safe
512   // way.
513   static bool IsHighResolutionTimerInUse();
514 #endif
515 
516   // Converts an exploded structure representing either the local time or UTC
517   // into a Time class.
FromUTCExploded(const Exploded & exploded)518   static Time FromUTCExploded(const Exploded& exploded) {
519     return FromExploded(false, exploded);
520   }
FromLocalExploded(const Exploded & exploded)521   static Time FromLocalExploded(const Exploded& exploded) {
522     return FromExploded(true, exploded);
523   }
524 
525 #if !defined(MOZ_SANDBOX)
526   // Converts a string representation of time to a Time object.
527   // An example of a time string which is converted is as below:-
528   // "Tue, 15 Nov 1994 12:45:26 GMT". If the timezone is not specified
529   // in the input string, FromString assumes local time and FromUTCString
530   // assumes UTC. A timezone that cannot be parsed (e.g. "UTC" which is not
531   // specified in RFC822) is treated as if the timezone is not specified.
532   // TODO(iyengar) Move the FromString/FromTimeT/ToTimeT/FromFileTime to
533   // a new time converter class.
FromString(const char * time_string,Time * parsed_time)534   static bool FromString(const char* time_string, Time* parsed_time) {
535     return FromStringInternal(time_string, true, parsed_time);
536   }
FromUTCString(const char * time_string,Time * parsed_time)537   static bool FromUTCString(const char* time_string, Time* parsed_time) {
538     return FromStringInternal(time_string, false, parsed_time);
539   }
540 #endif
541 
542   // Fills the given exploded structure with either the local time or UTC from
543   // this time structure (containing UTC).
UTCExplode(Exploded * exploded)544   void UTCExplode(Exploded* exploded) const {
545     return Explode(false, exploded);
546   }
LocalExplode(Exploded * exploded)547   void LocalExplode(Exploded* exploded) const {
548     return Explode(true, exploded);
549   }
550 
551   // Rounds this time down to the nearest day in local time. It will represent
552   // midnight on that day.
553   Time LocalMidnight() const;
554 
555  private:
556   friend class time_internal::TimeBase<Time>;
557 
Time(int64_t us)558   explicit Time(int64_t us) : TimeBase(us) {}
559 
560   // Explodes the given time to either local time |is_local = true| or UTC
561   // |is_local = false|.
562   void Explode(bool is_local, Exploded* exploded) const;
563 
564   // Unexplodes a given time assuming the source is either local time
565   // |is_local = true| or UTC |is_local = false|.
566   static Time FromExploded(bool is_local, const Exploded& exploded);
567 
568 #if !defined(MOZ_SANDBOX)
569   // Converts a string representation of time to a Time object.
570   // An example of a time string which is converted is as below:-
571   // "Tue, 15 Nov 1994 12:45:26 GMT". If the timezone is not specified
572   // in the input string, local time |is_local = true| or
573   // UTC |is_local = false| is assumed. A timezone that cannot be parsed
574   // (e.g. "UTC" which is not specified in RFC822) is treated as if the
575   // timezone is not specified.
576   static bool FromStringInternal(const char* time_string,
577                                  bool is_local,
578                                  Time* parsed_time);
579 #endif
580 };
581 
582 // Inline the TimeDelta factory methods, for fast TimeDelta construction.
583 
584 // static
FromDays(int days)585 inline TimeDelta TimeDelta::FromDays(int days) {
586   if (days == std::numeric_limits<int>::max())
587     return Max();
588   return TimeDelta(days * Time::kMicrosecondsPerDay);
589 }
590 
591 // static
FromHours(int hours)592 inline TimeDelta TimeDelta::FromHours(int hours) {
593   if (hours == std::numeric_limits<int>::max())
594     return Max();
595   return TimeDelta(hours * Time::kMicrosecondsPerHour);
596 }
597 
598 // static
FromMinutes(int minutes)599 inline TimeDelta TimeDelta::FromMinutes(int minutes) {
600   if (minutes == std::numeric_limits<int>::max())
601     return Max();
602   return TimeDelta(minutes * Time::kMicrosecondsPerMinute);
603 }
604 
605 // static
FromSeconds(int64_t secs)606 inline TimeDelta TimeDelta::FromSeconds(int64_t secs) {
607   return TimeDelta(secs) * Time::kMicrosecondsPerSecond;
608 }
609 
610 // static
FromMilliseconds(int64_t ms)611 inline TimeDelta TimeDelta::FromMilliseconds(int64_t ms) {
612   return TimeDelta(ms) * Time::kMicrosecondsPerMillisecond;
613 }
614 
615 // static
FromSecondsD(double secs)616 inline TimeDelta TimeDelta::FromSecondsD(double secs) {
617   return FromDouble(secs * Time::kMicrosecondsPerSecond);
618 }
619 
620 // static
FromMillisecondsD(double ms)621 inline TimeDelta TimeDelta::FromMillisecondsD(double ms) {
622   return FromDouble(ms * Time::kMicrosecondsPerMillisecond);
623 }
624 
625 // static
FromMicroseconds(int64_t us)626 inline TimeDelta TimeDelta::FromMicroseconds(int64_t us) {
627   return TimeDelta(us);
628 }
629 
630 // static
FromDouble(double value)631 inline TimeDelta TimeDelta::FromDouble(double value) {
632   double max_magnitude = std::numeric_limits<int64_t>::max();
633   TimeDelta delta = TimeDelta(static_cast<int64_t>(value));
634   if (value > max_magnitude)
635     delta = Max();
636   else if (value < -max_magnitude)
637     delta = -Max();
638   return delta;
639 }
640 
641 // For logging use only.
642 BASE_EXPORT std::ostream& operator<<(std::ostream& os, Time time);
643 
644 // TimeTicks ------------------------------------------------------------------
645 
646 // Represents monotonically non-decreasing clock time.
647 class BASE_EXPORT TimeTicks : public time_internal::TimeBase<TimeTicks> {
648  public:
TimeTicks()649   TimeTicks() : TimeBase(0) {
650   }
651 
652   // Platform-dependent tick count representing "right now." When
653   // IsHighResolution() returns false, the resolution of the clock could be
654   // as coarse as ~15.6ms. Otherwise, the resolution should be no worse than one
655   // microsecond.
656   static TimeTicks Now();
657 
658   // Returns true if the high resolution clock is working on this system and
659   // Now() will return high resolution values. Note that, on systems where the
660   // high resolution clock works but is deemed inefficient, the low resolution
661   // clock will be used instead.
662   static bool IsHighResolution();
663 
664 #if defined(OS_WIN)
665   // Translates an absolute QPC timestamp into a TimeTicks value. The returned
666   // value has the same origin as Now(). Do NOT attempt to use this if
667   // IsHighResolution() returns false.
668   static TimeTicks FromQPCValue(LONGLONG qpc_value);
669 #endif
670 
671   // Get an estimate of the TimeTick value at the time of the UnixEpoch. Because
672   // Time and TimeTicks respond differently to user-set time and NTP
673   // adjustments, this number is only an estimate. Nevertheless, this can be
674   // useful when you need to relate the value of TimeTicks to a real time and
675   // date. Note: Upon first invocation, this function takes a snapshot of the
676   // realtime clock to establish a reference point.  This function will return
677   // the same value for the duration of the application, but will be different
678   // in future application runs.
679   static TimeTicks UnixEpoch();
680 
681   // Returns |this| snapped to the next tick, given a |tick_phase| and
682   // repeating |tick_interval| in both directions. |this| may be before,
683   // after, or equal to the |tick_phase|.
684   TimeTicks SnappedToNextTick(TimeTicks tick_phase,
685                               TimeDelta tick_interval) const;
686 
687 #if defined(OS_WIN)
688  protected:
689   typedef DWORD (*TickFunctionType)(void);
690   static TickFunctionType SetMockTickFunction(TickFunctionType ticker);
691 #endif
692 
693  private:
694   friend class time_internal::TimeBase<TimeTicks>;
695 
696   // Please use Now() to create a new object. This is for internal use
697   // and testing.
TimeTicks(int64_t us)698   explicit TimeTicks(int64_t us) : TimeBase(us) {}
699 };
700 
701 // For logging use only.
702 BASE_EXPORT std::ostream& operator<<(std::ostream& os, TimeTicks time_ticks);
703 
704 // ThreadTicks ----------------------------------------------------------------
705 
706 // Represents a clock, specific to a particular thread, than runs only while the
707 // thread is running.
708 class BASE_EXPORT ThreadTicks : public time_internal::TimeBase<ThreadTicks> {
709  public:
ThreadTicks()710   ThreadTicks() : TimeBase(0) {
711   }
712 
713   // Returns true if ThreadTicks::Now() is supported on this system.
IsSupported()714   static bool IsSupported() {
715 #if (defined(_POSIX_THREAD_CPUTIME) && (_POSIX_THREAD_CPUTIME >= 0)) || \
716     (defined(OS_MACOSX) && !defined(OS_IOS)) || defined(OS_ANDROID)
717     return true;
718 #elif defined(OS_WIN)
719     return IsSupportedWin();
720 #else
721     return false;
722 #endif
723   }
724 
725   // Waits until the initialization is completed. Needs to be guarded with a
726   // call to IsSupported().
WaitUntilInitialized()727   static void WaitUntilInitialized() {
728 #if defined(OS_WIN)
729     WaitUntilInitializedWin();
730 #endif
731   }
732 
733   // Returns thread-specific CPU-time on systems that support this feature.
734   // Needs to be guarded with a call to IsSupported(). Use this timer
735   // to (approximately) measure how much time the calling thread spent doing
736   // actual work vs. being de-scheduled. May return bogus results if the thread
737   // migrates to another CPU between two calls. Returns an empty ThreadTicks
738   // object until the initialization is completed. If a clock reading is
739   // absolutely needed, call WaitUntilInitialized() before this method.
740   static ThreadTicks Now();
741 
742  private:
743   friend class time_internal::TimeBase<ThreadTicks>;
744 
745   // Please use Now() to create a new object. This is for internal use
746   // and testing.
ThreadTicks(int64_t us)747   explicit ThreadTicks(int64_t us) : TimeBase(us) {}
748 
749 #if defined(OS_WIN)
750   FRIEND_TEST_ALL_PREFIXES(TimeTicks, TSCTicksPerSecond);
751 
752   // Returns the frequency of the TSC in ticks per second, or 0 if it hasn't
753   // been measured yet. Needs to be guarded with a call to IsSupported().
754   // This method is declared here rather than in the anonymous namespace to
755   // allow testing.
756   static double TSCTicksPerSecond();
757 
758   static bool IsSupportedWin();
759   static void WaitUntilInitializedWin();
760 #endif
761 };
762 
763 // For logging use only.
764 BASE_EXPORT std::ostream& operator<<(std::ostream& os, ThreadTicks time_ticks);
765 
766 }  // namespace base
767 
768 #endif  // BASE_TIME_TIME_H_
769