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