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