Home | History | Annotate | Download | only in time
      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:
    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.
    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.
    136   int64_t ToInternalValue() const { return delta_; }
    137 
    138   // Returns the magnitude (absolute value) of this TimeDelta.
    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.
    148   bool is_zero() const {
    149     return delta_ == 0;
    150   }
    151 
    152   // Returns true if the time delta is the maximum time delta.
    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.
    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.
    303   bool is_null() const {
    304     return us_ == 0;
    305   }
    306 
    307   // Returns true if this object represents the maximum time.
    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.
    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.
    365   static TimeClass FromInternalValue(int64_t us) { return TimeClass(us); }
    366 
    367  protected:
    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 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.
    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.
    518   static Time FromUTCExploded(const Exploded& exploded) {
    519     return FromExploded(false, exploded);
    520   }
    521   static Time FromLocalExploded(const Exploded& exploded) {
    522     return FromExploded(true, exploded);
    523   }
    524 
    525   // Fills the given exploded structure with either the local time or UTC from
    526   // this time structure (containing UTC).
    527   void UTCExplode(Exploded* exploded) const {
    528     return Explode(false, exploded);
    529   }
    530   void LocalExplode(Exploded* exploded) const {
    531     return Explode(true, exploded);
    532   }
    533 
    534   // Rounds this time down to the nearest day in local time. It will represent
    535   // midnight on that day.
    536   Time LocalMidnight() const;
    537 
    538  private:
    539   friend class time_internal::TimeBase<Time>;
    540 
    541   explicit Time(int64_t us) : TimeBase(us) {}
    542 
    543   // Explodes the given time to either local time |is_local = true| or UTC
    544   // |is_local = false|.
    545   void Explode(bool is_local, Exploded* exploded) const;
    546 
    547   // Unexplodes a given time assuming the source is either local time
    548   // |is_local = true| or UTC |is_local = false|.
    549   static Time FromExploded(bool is_local, const Exploded& exploded);
    550 };
    551 
    552 // Inline the TimeDelta factory methods, for fast TimeDelta construction.
    553 
    554 // static
    555 inline TimeDelta TimeDelta::FromDays(int days) {
    556   if (days == std::numeric_limits<int>::max())
    557     return Max();
    558   return TimeDelta(days * Time::kMicrosecondsPerDay);
    559 }
    560 
    561 // static
    562 inline TimeDelta TimeDelta::FromHours(int hours) {
    563   if (hours == std::numeric_limits<int>::max())
    564     return Max();
    565   return TimeDelta(hours * Time::kMicrosecondsPerHour);
    566 }
    567 
    568 // static
    569 inline TimeDelta TimeDelta::FromMinutes(int minutes) {
    570   if (minutes == std::numeric_limits<int>::max())
    571     return Max();
    572   return TimeDelta(minutes * Time::kMicrosecondsPerMinute);
    573 }
    574 
    575 // static
    576 inline TimeDelta TimeDelta::FromSeconds(int64_t secs) {
    577   return TimeDelta(secs) * Time::kMicrosecondsPerSecond;
    578 }
    579 
    580 // static
    581 inline TimeDelta TimeDelta::FromMilliseconds(int64_t ms) {
    582   return TimeDelta(ms) * Time::kMicrosecondsPerMillisecond;
    583 }
    584 
    585 // static
    586 inline TimeDelta TimeDelta::FromSecondsD(double secs) {
    587   return FromDouble(secs * Time::kMicrosecondsPerSecond);
    588 }
    589 
    590 // static
    591 inline TimeDelta TimeDelta::FromMillisecondsD(double ms) {
    592   return FromDouble(ms * Time::kMicrosecondsPerMillisecond);
    593 }
    594 
    595 // static
    596 inline TimeDelta TimeDelta::FromMicroseconds(int64_t us) {
    597   return TimeDelta(us);
    598 }
    599 
    600 // static
    601 inline TimeDelta TimeDelta::FromDouble(double value) {
    602   double max_magnitude = std::numeric_limits<int64_t>::max();
    603   TimeDelta delta = TimeDelta(static_cast<int64_t>(value));
    604   if (value > max_magnitude)
    605     delta = Max();
    606   else if (value < -max_magnitude)
    607     delta = -Max();
    608   return delta;
    609 }
    610 
    611 // For logging use only.
    612 BASE_EXPORT std::ostream& operator<<(std::ostream& os, Time time);
    613 
    614 // TimeTicks ------------------------------------------------------------------
    615 
    616 // Represents monotonically non-decreasing clock time.
    617 class TimeTicks : public time_internal::TimeBase<TimeTicks> {
    618  public:
    619   TimeTicks() : TimeBase(0) {
    620   }
    621 
    622   // Platform-dependent tick count representing "right now." When
    623   // IsHighResolution() returns false, the resolution of the clock could be
    624   // as coarse as ~15.6ms. Otherwise, the resolution should be no worse than one
    625   // microsecond.
    626   static TimeTicks Now();
    627 
    628   // Returns true if the high resolution clock is working on this system and
    629   // Now() will return high resolution values. Note that, on systems where the
    630   // high resolution clock works but is deemed inefficient, the low resolution
    631   // clock will be used instead.
    632   static bool IsHighResolution();
    633 
    634 #if defined(OS_WIN)
    635   // Translates an absolute QPC timestamp into a TimeTicks value. The returned
    636   // value has the same origin as Now(). Do NOT attempt to use this if
    637   // IsHighResolution() returns false.
    638   static TimeTicks FromQPCValue(LONGLONG qpc_value);
    639 #endif
    640 
    641   // Get an estimate of the TimeTick value at the time of the UnixEpoch. Because
    642   // Time and TimeTicks respond differently to user-set time and NTP
    643   // adjustments, this number is only an estimate. Nevertheless, this can be
    644   // useful when you need to relate the value of TimeTicks to a real time and
    645   // date. Note: Upon first invocation, this function takes a snapshot of the
    646   // realtime clock to establish a reference point.  This function will return
    647   // the same value for the duration of the application, but will be different
    648   // in future application runs.
    649   static TimeTicks UnixEpoch();
    650 
    651   // Returns |this| snapped to the next tick, given a |tick_phase| and
    652   // repeating |tick_interval| in both directions. |this| may be before,
    653   // after, or equal to the |tick_phase|.
    654   TimeTicks SnappedToNextTick(TimeTicks tick_phase,
    655                               TimeDelta tick_interval) const;
    656 
    657 #if defined(OS_WIN)
    658  protected:
    659   typedef DWORD (*TickFunctionType)(void);
    660   static TickFunctionType SetMockTickFunction(TickFunctionType ticker);
    661 #endif
    662 
    663  private:
    664   friend class time_internal::TimeBase<TimeTicks>;
    665 
    666   // Please use Now() to create a new object. This is for internal use
    667   // and testing.
    668   explicit TimeTicks(int64_t us) : TimeBase(us) {}
    669 };
    670 
    671 // For logging use only.
    672 std::ostream& operator<<(std::ostream& os, TimeTicks time_ticks);
    673 
    674 // ThreadTicks ----------------------------------------------------------------
    675 
    676 // Represents a clock, specific to a particular thread, than runs only while the
    677 // thread is running.
    678 class ThreadTicks : public time_internal::TimeBase<ThreadTicks> {
    679  public:
    680   ThreadTicks() : TimeBase(0) {
    681   }
    682 
    683   // Returns true if ThreadTicks::Now() is supported on this system.
    684   static bool IsSupported() {
    685 #if (defined(_POSIX_THREAD_CPUTIME) && (_POSIX_THREAD_CPUTIME >= 0)) || \
    686     (defined(OS_MACOSX) && !defined(OS_IOS)) || defined(OS_ANDROID)
    687     return true;
    688 #elif defined(OS_WIN)
    689     return IsSupportedWin();
    690 #else
    691     return false;
    692 #endif
    693   }
    694 
    695   // Waits until the initialization is completed. Needs to be guarded with a
    696   // call to IsSupported().
    697   static void WaitUntilInitialized() {
    698 #if defined(OS_WIN)
    699     WaitUntilInitializedWin();
    700 #endif
    701   }
    702 
    703   // Returns thread-specific CPU-time on systems that support this feature.
    704   // Needs to be guarded with a call to IsSupported(). Use this timer
    705   // to (approximately) measure how much time the calling thread spent doing
    706   // actual work vs. being de-scheduled. May return bogus results if the thread
    707   // migrates to another CPU between two calls. Returns an empty ThreadTicks
    708   // object until the initialization is completed. If a clock reading is
    709   // absolutely needed, call WaitUntilInitialized() before this method.
    710   static ThreadTicks Now();
    711 
    712  private:
    713   friend class time_internal::TimeBase<ThreadTicks>;
    714 
    715   // Please use Now() to create a new object. This is for internal use
    716   // and testing.
    717   explicit ThreadTicks(int64_t us) : TimeBase(us) {}
    718 
    719 };
    720 
    721 // For logging use only.
    722 std::ostream& operator<<(std::ostream& os, ThreadTicks time_ticks);
    723 
    724 }  // namespace base
    725 
    726 #endif  // BASE_TIME_TIME_H_
    727