| 6 |
| // internally represented as microseconds (s/1,000,000) since the Windows epoch |
| 7 | // (1601-01-01 00:00:00 UTC). System-dependent clock interface routines are |
| 8 | // defined in time_PLATFORM.cc. Note that values for Time may skew and jump |
| 9 | // around as the operating system makes adjustments to synchronize (e.g., with |
| 10 | // NTP servers). Thus, client code that uses the Time class must account for |
| 11 | // this. |
| 12 | // |
| 13 | // TimeDelta represents a duration of time, internally represented in |
| 14 | // microseconds. |
| 15 | // |
| 16 | // TimeTicks and ThreadTicks represent an abstract time that is most of the time |
| 17 | // incrementing, for use in measuring time durations. Internally, they are |
| 18 | // represented in microseconds. They cannot be converted to a human-readable |
| 19 | // time, but are guaranteed not to decrease (unlike the Time class). Note that |
| 20 | // TimeTicks may "stand still" (e.g., if the computer is suspended), and |
| 21 | // ThreadTicks will "stand still" whenever the thread has been de-scheduled by |
| 22 | // the operating system. |
| 23 | // |
| 24 | // All time classes are copyable, assignable, and occupy 64-bits per instance. |
| 25 | // As a result, prefer passing them by value: |
| 26 | // void MyFunction(TimeDelta arg); |
| 27 | // If circumstances require, you may also pass by const reference: |
| 28 | // void MyFunction(const TimeDelta& arg); // Not preferred. |
| 29 | // |
| 30 | // Definitions of operator<< are provided to make these types work with |
| 31 | // DCHECK_EQ() and other log macros. For human-readable formatting, see |
| 32 | // "base/i18n/time_formatting.h". |
| 33 | // |
| 34 | // So many choices! Which time class should you use? Examples: |
| 35 | // |
| 36 | // Time: Interpreting the wall-clock time provided by a remote system. |
| 37 | // Detecting whether cached resources have expired. Providing the |
| 38 | // user with a display of the current date and time. Determining |
| 39 | // the amount of time between events across re-boots of the |
| 40 | // machine. |
| 41 | // |
| 42 | // TimeTicks: Tracking the amount of time a task runs. Executing delayed |
| 43 | // tasks at the right time. Computing presentation timestamps. |
| 44 | // Synchronizing audio and video using TimeTicks as a common |
| 45 | // reference clock (lip-sync). Measuring network round-trip |
| 46 | // latency. |
| 47 | // |
| 48 | // ThreadTicks: Benchmarking how long the current thread has been doing actual |
| 49 | // work. |
| 50 |
| 51 | #ifndef BASE_TIME_TIME_H_ |
| 52 | #define BASE_TIME_TIME_H_ |
| 53 |
| 54 | #include <stdint.h> |
| 55 | #include <time.h> |
| 56 |
| 57 | #include <iosfwd> |
| 58 | #include <limits> |
| 59 |
| 60 | #include "base/base_export.h" |
| 61 | #include "base/compiler_specific.h" |
| 62 | #include "base/logging.h" |
| 63 | #include "base/numerics/safe_math.h" |
| 64 | #include "build/build_config.h" |
| 65 |
| 66 | #if defined(OS_FUCHSIA) |
| 67 | #include <zircon/types.h> |
| 68 | #endif |
| 69 |
| 70 | #if defined(OS_MACOSX) |
| 71 | #include <CoreFoundation/CoreFoundation.h> |
| 72 | // Avoid Mac system header macro leak. |
| 73 | #undef TYPE_BOOL |
| 74 | #endif |
| 75 |
| 76 | #if defined(OS_ANDROID) |
| 77 | #include <jni.h> |
| 78 | #endif |
| 79 |
| 80 | #if defined(OS_POSIX) || defined(OS_FUCHSIA) |
| 81 | #include <unistd.h> |
| 82 | #include <sys/time.h> |
| 83 | #endif |
| 84 |
| 85 | #if defined(OS_WIN) |
| 86 | #include "base/gtest_prod_util.h" |
| 87 | #include "base/win/windows_types.h" |
| 88 | #endif |
| 89 |
| 90 | namespace ABI { |
| 91 | namespace Windows { |
| 92 | namespace Foundation { |
| 93 | struct DateTime; |
| 94 | } // namespace Foundation |
| 95 | } // namespace Windows |
| 96 | } // namespace ABI |
| 97 |
| 98 | namespace base { |
| 99 |
| 100 | class PlatformThreadHandle; |
| 101 | class TimeDelta; |
| 102 |
| 103 | // The functions in the time_internal namespace are meant to be used only by the |
| 104 | // time classes and functions. Please use the math operators defined in the |
| 105 | // time classes instead. |
| 106 | namespace time_internal { |
| 107 |
| 108 | // Add or subtract a TimeDelta from |value|. TimeDelta::Min()/Max() are treated |
| 109 | // as infinity and will always saturate the return value (infinity math applies |
| 110 | // if |value| also is at either limit of its spectrum). The int64_t argument and |
| 111 | // return value are in terms of a microsecond timebase. |
| 112 | BASE_EXPORT constexpr int64_t SaturatedAdd(int64_t value, TimeDelta delta); |
| 113 | BASE_EXPORT constexpr int64_t SaturatedSub(int64_t value, TimeDelta delta); |
| 114 |
| 115 | } // namespace time_internal |
| 116 |
| 117 | // TimeDelta ------------------------------------------------------------------ |
| 118 |
| 119 | class BASE_EXPORT TimeDelta { |
| 120 | public: |
| 121 | constexpr TimeDelta() : delta_(0) {} |
| 122 |
| 123 | // Converts units of time to TimeDeltas. |
| 124 | // These conversions treat minimum argument values as min type values or -inf, |
| 125 | // and maximum ones as max type values or +inf; and their results will produce |
| 126 | // an is_min() or is_max() TimeDelta. WARNING: Floating point arithmetic is |
| 127 | // such that FromXXXD(t.InXXXF()) may not precisely equal |t|. Hence, floating |
| 128 | // point values should not be used for storage. |
| 129 | static constexpr TimeDelta FromDays(int days); |
| 130 | static constexpr TimeDelta FromHours(int hours); |
| 131 | static constexpr TimeDelta FromMinutes(int minutes); |
| 132 | static constexpr TimeDelta FromSeconds(int64_t secs); |
| 133 | static constexpr TimeDelta FromMilliseconds(int64_t ms); |
| 134 | static constexpr TimeDelta FromMicroseconds(int64_t us); |
| 135 | static constexpr TimeDelta FromNanoseconds(int64_t ns); |
| 136 | static constexpr TimeDelta FromSecondsD(double secs); |
| 137 | static constexpr TimeDelta FromMillisecondsD(double ms); |
| 138 | static constexpr TimeDelta FromMicrosecondsD(double us); |
| 139 | static constexpr TimeDelta FromNanosecondsD(double ns); |
| 140 | #if defined(OS_WIN) |
| 141 | static TimeDelta FromQPCValue(LONGLONG qpc_value); |
| 142 | // TODO(crbug.com/989694): Avoid base::TimeDelta factory functions |
| 143 | // based on absolute time |
| 144 | static TimeDelta FromFileTime(FILETIME ft); |
| 145 | static TimeDelta FromWinrtDateTime(ABI::Windows::Foundation::DateTime dt); |
| 146 | #elif defined(OS_POSIX) || defined(OS_FUCHSIA) |
| 147 | static TimeDelta FromTimeSpec(const timespec& ts); |
| 148 | #endif |
| 149 | #if defined(OS_FUCHSIA) |
| 150 | static TimeDelta FromZxDuration(zx_duration_t nanos); |
| 151 | #endif |
| 152 |
| 153 | // Converts an integer value representing TimeDelta to a class. This is used |
| 154 | // when deserializing a |TimeDelta| structure, using a value known to be |
| 155 | // compatible. It is not provided as a constructor because the integer type |
| 156 | // may be unclear from the perspective of a caller. |
| 157 | // |
| 158 | // DEPRECATED - Do not use in new code. http://crbug.com/634507 |
| 159 | static constexpr TimeDelta FromInternalValue(int64_t delta) { |
| 160 | return TimeDelta(delta); |
| 161 | } |
| 162 |
| 163 | // Returns the maximum time delta, which should be greater than any reasonable |
| 164 | // time delta we might compare it to. Adding or subtracting the maximum time |
| 165 | // delta to a time or another time delta has an undefined result. |
| 166 | static constexpr TimeDelta Max(); |
| 167 |
| 168 | // Returns the minimum time delta, which should be less than than any |
| 169 | // reasonable time delta we might compare it to. Adding or subtracting the |
| 170 | // minimum time delta to a time or another time delta has an undefined result. |
| 171 | static constexpr TimeDelta Min(); |
| 172 |
| 173 | // Returns the internal numeric value of the TimeDelta object. Please don't |
| 174 | // use this and do arithmetic on it, as it is more error prone than using the |
| 175 | // provided operators. |
| 176 | // For serializing, use FromInternalValue to reconstitute. |
| 177 | // |
| 178 | // DEPRECATED - Do not use in new code. http://crbug.com/634507 |
| 179 | constexpr int64_t ToInternalValue() const { return delta_; } |
| 180 |
| 181 | // Returns the magnitude (absolute value) of this TimeDelta. |
| 182 | constexpr TimeDelta magnitude() const { |
| 183 | // Some toolchains provide an incomplete C++11 implementation and lack an |
| 184 | // int64_t overload for std::abs(). The following is a simple branchless |
| 185 | // implementation: |
| 186 | const int64_t mask = delta_ >> (sizeof(delta_) * 8 - 1); |
| 187 | return TimeDelta((delta_ + mask) ^ mask); |
| 188 | } |
| 189 |
| 190 | // Returns true if the time delta is zero. |
| 191 | constexpr bool is_zero() const { return delta_ == 0; } |
| 192 |
| 193 | // Returns true if the time delta is the maximum/minimum time delta. |
| 194 | constexpr bool is_max() const { |
| 195 | return delta_ == std::numeric_limits<int64_t>::max(); |
| 196 | } |
| 197 | constexpr bool is_min() const { |
| 198 | return delta_ == std::numeric_limits<int64_t>::min(); |
| 199 | } |
| 200 |
| 201 | #if defined(OS_POSIX) || defined(OS_FUCHSIA) |
| 202 | struct timespec ToTimeSpec() const; |
| 203 | #endif |
| 204 | #if defined(OS_FUCHSIA) |
| 205 | zx_duration_t ToZxDuration() const; |
| 206 | #endif |
| 207 | #if defined(OS_WIN) |
| 208 | ABI::Windows::Foundation::DateTime ToWinrtDateTime() const; |
| 209 | #endif |
| 210 |
| 211 | // Returns the time delta in some unit. Minimum argument values return as |
| 212 | // -inf for doubles and min type values otherwise. Maximum ones are treated as |
| 213 | // +inf for doubles and max type values otherwise. Their results will produce |
| 214 | // an is_min() or is_max() TimeDelta. The InXYZF versions return a floating |
| 215 | // point value. The InXYZ versions return a truncated value (aka rounded |
| 216 | // towards zero, std::trunc() behavior). The InXYZFloored() versions round to |
| 217 | // lesser integers (std::floor() behavior). The XYZRoundedUp() versions round |
| 218 | // up to greater integers (std::ceil() behavior). WARNING: Floating point |
| 219 | // arithmetic is such that FromXXXD(t.InXXXF()) may not precisely equal |t|. |
| 220 | // Hence, floating point values should not be used for storage. |
| 221 | int InDays() const; |
| 222 | int InDaysFloored() const; |
| 223 | int InHours() const; |
| 224 | int InMinutes() const; |
| 225 | double InSecondsF() const; |
| 226 | int64_t InSeconds() const; |
| 227 | double InMillisecondsF() const; |
| 228 | int64_t InMilliseconds() const; |
| 229 | int64_t InMillisecondsRoundedUp() const; |
| 230 | constexpr int64_t InMicroseconds() const { return delta_; } |
| 231 | double InMicrosecondsF() const; |
| 232 | int64_t InNanoseconds() const; |
| 233 |
| 234 | // Computations with other deltas. |
| 235 | constexpr TimeDelta operator+(TimeDelta other) const { |
| 236 | return TimeDelta(time_internal::SaturatedAdd(delta_, other)); |
| 237 | } |
| 238 | constexpr TimeDelta operator-(TimeDelta other) const { |
| 239 | return TimeDelta(time_internal::SaturatedSub(delta_, other)); |
| 240 | } |
| 241 |
| 242 | constexpr TimeDelta& operator+=(TimeDelta other) { |
| 243 | return *this = (*this + other); |
| 244 | } |
| 245 | constexpr TimeDelta& operator-=(TimeDelta other) { |
| 246 | return *this = (*this - other); |
| 247 | } |
| 248 | constexpr TimeDelta operator-() const { |
| 249 | if (is_max()) { |
| 250 | return Min(); |
| 251 | } |
| 252 | if (is_min()) { |
| 253 | return Max(); |
| 254 | } |
| 255 | return TimeDelta(-delta_); |
| 256 | } |
| 257 |
| 258 | // Computations with numeric types. |
| 259 | template <typename T> |
| 260 | constexpr TimeDelta operator*(T a) const { |
| 261 | CheckedNumeric<int64_t> rv(delta_); |
| 262 | rv *= a; |
| 263 | if (rv.IsValid()) |
| 264 | return TimeDelta(rv.ValueOrDie()); |
| 265 | // Matched sign overflows. Mismatched sign underflows. |
| 266 | if ((delta_ < 0) ^ (a < 0)) |
| 267 | return TimeDelta(std::numeric_limits<int64_t>::min()); |
| 268 | return TimeDelta(std::numeric_limits<int64_t>::max()); |
| 269 | } |
| 270 | template <typename T> |
| 271 | constexpr TimeDelta operator/(T a) const { |
| 272 | CheckedNumeric<int64_t> rv(delta_); |
| 273 | rv /= a; |
| 274 | if (rv.IsValid()) |
| 275 | return TimeDelta(rv.ValueOrDie()); |
| 276 | // Matched sign overflows. Mismatched sign underflows. |
| 277 | // Special case to catch divide by zero. |
| 278 | if ((delta_ < 0) ^ (a <= 0)) |
| 279 | return TimeDelta(std::numeric_limits<int64_t>::min()); |
| 280 | return TimeDelta(std::numeric_limits<int64_t>::max()); |
| 281 | } |
| 282 | template <typename T> |
| 283 | constexpr TimeDelta& operator*=(T a) { |
| 284 | return *this = (*this * a); |
| 285 | } |
| 286 | template <typename T> |
| 287 | constexpr TimeDelta& operator/=(T a) { |
| 288 | return *this = (*this / a); |
| 289 | } |
| 290 |
| 291 | constexpr int64_t operator/(TimeDelta a) const { |
| 292 | if (a.delta_ == 0) { |
| 293 | return delta_ < 0 ? std::numeric_limits<int64_t>::min() |
| 294 | : std::numeric_limits<int64_t>::max(); |
| 295 | } |
| 296 | if (is_max()) { |
| 297 | if (a.delta_ < 0) { |
| 298 | return std::numeric_limits<int64_t>::min(); |
| 299 | } |
| 300 | return std::numeric_limits<int64_t>::max(); |
| 301 | } |
| 302 | if (is_min()) { |
| 303 | if (a.delta_ > 0) { |
| 304 | return std::numeric_limits<int64_t>::min(); |
| 305 | } |
| 306 | return std::numeric_limits<int64_t>::max(); |
| 307 | } |
| 308 | if (a.is_max()) { |
| 309 | return 0; |
| 310 | } |
| 311 | return delta_ / a.delta_; |
| 312 | } |
| 313 |
| 314 | constexpr TimeDelta operator%(TimeDelta a) const { |
| 315 | if (a.is_min() || a.is_max()) { |
| 316 | return TimeDelta(delta_); |
| 317 | } |
| 318 | return TimeDelta(delta_ % a.delta_); |
| 319 | } |
| 320 | TimeDelta& operator%=(TimeDelta other) { return *this = (*this % other); } |
| 321 |
| 322 | // Comparison operators. |
| 323 | constexpr bool operator==(TimeDelta other) const { |
| 324 | return delta_ == other.delta_; |
| 325 | } |
| 326 | constexpr bool operator!=(TimeDelta other) const { |
| 327 | return delta_ != other.delta_; |
| 328 | } |
| 329 | constexpr bool operator<(TimeDelta other) const { |
| 330 | return delta_ < other.delta_; |
| 331 | } |
| 332 | constexpr bool operator<=(TimeDelta other) const { |
| 333 | return delta_ <= other.delta_; |
| 334 | } |
| 335 | constexpr bool operator>(TimeDelta other) const { |
| 336 | return delta_ > other.delta_; |
| 337 | } |
| 338 | constexpr bool operator>=(TimeDelta other) const { |
| 339 | return delta_ >= other.delta_; |
| 340 | } |
| 341 |
| 342 | private: |
| 343 | friend constexpr int64_t time_internal::SaturatedAdd(int64_t value, |
| 344 | TimeDelta delta); |
| 345 | friend constexpr int64_t time_internal::SaturatedSub(int64_t value, |
| 346 | TimeDelta delta); |
| 347 |
| 348 | // Constructs a delta given the duration in microseconds. This is private |
| 349 | // to avoid confusion by callers with an integer constructor. Use |
| 350 | // FromSeconds, FromMilliseconds, etc. instead. |
| 351 | constexpr explicit TimeDelta(int64_t delta_us) : delta_(delta_us) {} |
| 352 |
| 353 | // Private method to build a delta from a double. |
| 354 | static constexpr TimeDelta FromDouble(double value); |
| 355 |
| 356 | // Private method to build a delta from the product of a user-provided value |
| 357 | // and a known-positive value. |
| 358 | static constexpr TimeDelta FromProduct(int64_t value, int64_t positive_value); |
| 359 |
| 360 | // Delta in microseconds. |
| 361 | int64_t delta_; |
| 362 | }; |
| 363 |
| 364 | template <typename T> |
| 365 | constexpr TimeDelta operator*(T a, TimeDelta td) { |
| 366 | return td * a; |
| 367 | } |
| 368 |
| 369 | // For logging use only. |
| 370 | BASE_EXPORT std::ostream& operator<<(std::ostream& os, TimeDelta time_delta); |
| 371 |
| 372 | // Do not reference the time_internal::TimeBase template class directly. Please |
| 373 | // use one of the time subclasses instead, and only reference the public |
| 374 | // TimeBase members via those classes. |
| 375 | namespace time_internal { |
| 376 |
| 377 | constexpr int64_t SaturatedAdd(int64_t value, TimeDelta delta) { |
| 378 | // Treat Min/Max() as +/- infinity (additions involving two infinities are |
| 379 | // only valid if signs match). |
| 380 | if (delta.is_max()) { |
| 381 | CHECK_GT(value, std::numeric_limits<int64_t>::min()); |
| 382 | return std::numeric_limits<int64_t>::max(); |
| 383 | } else if (delta.is_min()) { |
| 384 | CHECK_LT(value, std::numeric_limits<int64_t>::max()); |
| 385 | return std::numeric_limits<int64_t>::min(); |
| 386 | } |
| 387 |
| 388 | return base::ClampAdd(value, delta.delta_); |
| 389 | } |
| 390 |
| 391 | constexpr int64_t SaturatedSub(int64_t value, TimeDelta delta) { |
| 392 | // Treat Min/Max() as +/- infinity (subtractions involving two infinities are |
| 393 | // only valid if signs are opposite). |
| 394 | if (delta.is_max()) { |
| 395 | CHECK_LT(value, std::numeric_limits<int64_t>::max()); |
| 396 | return std::numeric_limits<int64_t>::min(); |
| 397 | } else if (delta.is_min()) { |
| 398 | CHECK_GT(value, std::numeric_limits<int64_t>::min()); |
| 399 | return std::numeric_limits<int64_t>::max(); |
| 400 | } |
| 401 |
| 402 | return base::ClampSub(value, delta.delta_); |
| 403 | } |
| 404 |
| 405 | // TimeBase-------------------------------------------------------------------- |
| 406 |
| 407 | // Provides value storage and comparison/math operations common to all time |
| 408 | // classes. Each subclass provides for strong type-checking to ensure |
| 409 | // semantically meaningful comparison/math of time values from the same clock |
| 410 | // source or timeline. |
| 411 | template<class TimeClass> |
| 412 | class TimeBase { |
| 413 | public: |
| 414 | static constexpr int64_t kHoursPerDay = 24; |
| 415 | static constexpr int64_t kSecondsPerMinute = 60; |
| 416 | static constexpr int64_t kSecondsPerHour = 60 * kSecondsPerMinute; |
| 417 | static constexpr int64_t kMillisecondsPerSecond = 1000; |
| 418 | static constexpr int64_t kMillisecondsPerDay = |
| 419 | kMillisecondsPerSecond * 60 * 60 * kHoursPerDay; |
| 420 | static constexpr int64_t kMicrosecondsPerMillisecond = 1000; |
| 421 | static constexpr int64_t kMicrosecondsPerSecond = |
| 422 | kMicrosecondsPerMillisecond * kMillisecondsPerSecond; |
| 423 | static constexpr int64_t kMicrosecondsPerMinute = kMicrosecondsPerSecond * 60; |
| 424 | static constexpr int64_t kMicrosecondsPerHour = kMicrosecondsPerMinute * 60; |
| 425 | static constexpr int64_t kMicrosecondsPerDay = |
| 426 | kMicrosecondsPerHour * kHoursPerDay; |
| 427 | static constexpr int64_t kMicrosecondsPerWeek = kMicrosecondsPerDay * 7; |
| 428 | static constexpr int64_t kNanosecondsPerMicrosecond = 1000; |
| 429 | static constexpr int64_t kNanosecondsPerSecond = |
| 430 | kNanosecondsPerMicrosecond * kMicrosecondsPerSecond; |
| 431 |
| 432 | // Returns true if this object has not been initialized. |
| 433 | // |
| 434 | // Warning: Be careful when writing code that performs math on time values, |
| 435 | // since it's possible to produce a valid "zero" result that should not be |
| 436 | // interpreted as a "null" value. |
| 437 | constexpr bool is_null() const { return us_ == 0; } |
| 438 |
| 439 | // Returns true if this object represents the maximum/minimum time. |
| 440 | constexpr bool is_max() const { |
| 441 | return us_ == std::numeric_limits<int64_t>::max(); |
| 442 | } |
| 443 | constexpr bool is_min() const { |
| 444 | return us_ == std::numeric_limits<int64_t>::min(); |
| 445 | } |
| 446 |
| 447 | // Returns the maximum/minimum times, which should be greater/less than than |
| 448 | // any reasonable time with which we might compare it. |
| 449 | static constexpr TimeClass Max() { |
| 450 | return TimeClass(std::numeric_limits<int64_t>::max()); |
| 451 | } |
| 452 |
| 453 | static constexpr TimeClass Min() { |
| 454 | return TimeClass(std::numeric_limits<int64_t>::min()); |
| 455 | } |
| 456 |
| 457 | // For serializing only. Use FromInternalValue() to reconstitute. Please don't |
| 458 | // use this and do arithmetic on it, as it is more error prone than using the |
| 459 | // provided operators. |
| 460 | // |
| 461 | // DEPRECATED - Do not use in new code. For serializing Time values, prefer |
| 462 | // Time::ToDeltaSinceWindowsEpoch().InMicroseconds(). http://crbug.com/634507 |
| 463 | constexpr int64_t ToInternalValue() const { return us_; } |
| 464 |
| 465 | // The amount of time since the origin (or "zero") point. This is a syntactic |
| 466 | // convenience to aid in code readability, mainly for debugging/testing use |
| 467 | // cases. |
| 468 | // |
| 469 | // Warning: While the Time subclass has a fixed origin point, the origin for |
| 470 | // the other subclasses can vary each time the application is restarted. |
| 471 | constexpr TimeDelta since_origin() const { |
| 472 | return TimeDelta::FromMicroseconds(us_); |
| 473 | } |
| 474 |
| 475 | constexpr TimeClass& operator=(TimeClass other) { |
| 476 | us_ = other.us_; |
| 477 | return *(static_cast<TimeClass*>(this)); |
| 478 | } |
| 479 |
| 480 | // Compute the difference between two times. |
| 481 | constexpr TimeDelta operator-(TimeClass other) const { |
| 482 | return TimeDelta::FromMicroseconds(us_ - other.us_); |
| 483 | } |
| 484 |
| 485 | // Return a new time modified by some delta. |
| 486 | constexpr TimeClass operator+(TimeDelta delta) const { |
| 487 | return TimeClass(time_internal::SaturatedAdd(us_, delta)); |
| 488 | } |
| 489 | constexpr TimeClass operator-(TimeDelta delta) const { |
| 490 | return TimeClass(time_internal::SaturatedSub(us_, delta)); |
| 491 | } |
| 492 |
| 493 | // Modify by some time delta. |
| 494 | constexpr TimeClass& operator+=(TimeDelta delta) { |
| 495 | return static_cast<TimeClass&>(*this = (*this + delta)); |
| 496 | } |
| 497 | constexpr TimeClass& operator-=(TimeDelta delta) { |
| 498 | return static_cast<TimeClass&>(*this = (*this - delta)); |
| 499 | } |
| 500 |
| 501 | // Comparison operators |
| 502 | constexpr bool operator==(TimeClass other) const { return us_ == other.us_; } |
| 503 | constexpr bool operator!=(TimeClass other) const { return us_ != other.us_; } |
| 504 | constexpr bool operator<(TimeClass other) const { return us_ < other.us_; } |
| 505 | constexpr bool operator<=(TimeClass other) const { return us_ <= other.us_; } |
| 506 | constexpr bool operator>(TimeClass other) const { return us_ > other.us_; } |
| 507 | constexpr bool operator>=(TimeClass other) const { return us_ >= other.us_; } |
| 508 |
| 509 | protected: |
| 510 | constexpr explicit TimeBase(int64_t us) : us_(us) {} |
| 511 |
| 512 | // Time value in a microsecond timebase. |
| 513 | int64_t us_; |
| 514 | }; |
| 515 |
| 516 | } // namespace time_internal |
| 517 |
| 518 | template <class TimeClass> |
| 519 | inline constexpr TimeClass operator+(TimeDelta delta, TimeClass t) { |
| 520 | return t + delta; |
| 521 | } |
| 522 |
| 523 | // Time ----------------------------------------------------------------------- |
| 524 |
| 525 | // Represents a wall clock time in UTC. Values are not guaranteed to be |
| 526 | // monotonically non-decreasing and are subject to large amounts of skew. |
| 527 | // Time is stored internally as microseconds since the Windows epoch (1601). |
| 528 | class BASE_EXPORT Time : public time_internal::TimeBase<Time> { |
| 529 | public: |
| 530 | // Offset of UNIX epoch (1970-01-01 00:00:00 UTC) from Windows FILETIME epoch |
| 531 | // (1601-01-01 00:00:00 UTC), in microseconds. This value is derived from the |
| 532 | // following: ((1970-1601)*365+89)*24*60*60*1000*1000, where 89 is the number |
| 533 | // of leap year days between 1601 and 1970: (1970-1601)/4 excluding 1700, |
| 534 | // 1800, and 1900. |
| 535 | static constexpr int64_t kTimeTToMicrosecondsOffset = |
| 536 | INT64_C(11644473600000000); |
| 537 |
| 538 | #if defined(OS_WIN) |
| 539 | // To avoid overflow in QPC to Microseconds calculations, since we multiply |
| 540 | // by kMicrosecondsPerSecond, then the QPC value should not exceed |
| 541 | // (2^63 - 1) / 1E6. If it exceeds that threshold, we divide then multiply. |
| 542 | static constexpr int64_t kQPCOverflowThreshold = INT64_C(0x8637BD05AF7); |
| 543 | #endif |
| 544 |
| 545 | // kExplodedMinYear and kExplodedMaxYear define the platform-specific limits |
| 546 | // for values passed to FromUTCExploded() and FromLocalExploded(). Those |
| 547 | // functions will return false if passed values outside these limits. The limits |
| 548 | // are inclusive, meaning that the API should support all dates within a given |
| 549 | // limit year. |
| 550 | #if defined(OS_WIN) |
| 551 | static constexpr int kExplodedMinYear = 1601; |
| 552 | static constexpr int kExplodedMaxYear = 30827; |
| 553 | #elif defined(OS_IOS) && !__LP64__ |
| 554 | static constexpr int kExplodedMinYear = std::numeric_limits<int>::min(); |
| 555 | static constexpr int kExplodedMaxYear = std::numeric_limits<int>::max(); |
| 556 | #elif defined(OS_MACOSX) |
| 557 | static constexpr int kExplodedMinYear = 1902; |
| 558 | static constexpr int kExplodedMaxYear = std::numeric_limits<int>::max(); |
| 559 | #elif defined(OS_ANDROID) |
| 560 | // Though we use 64-bit time APIs on both 32 and 64 bit Android, some OS |
| 561 | // versions like KitKat (ARM but not x86 emulator) can't handle some early |
| 562 | // dates (e.g. before 1170). So we set min conservatively here. |
| 563 | static constexpr int kExplodedMinYear = 1902; |
| 564 | static constexpr int kExplodedMaxYear = std::numeric_limits<int>::max(); |
| 565 | #else |
| 566 | static constexpr int kExplodedMinYear = |
| 567 | (sizeof(time_t) == 4 ? 1902 : std::numeric_limits<int>::min()); |
| 568 | static constexpr int kExplodedMaxYear = |
| 569 | (sizeof(time_t) == 4 ? 2037 : std::numeric_limits<int>::max()); |
| 570 | #endif |
| 571 |
| 572 | // Represents an exploded time that can be formatted nicely. This is kind of |
| 573 | // like the Win32 SYSTEMTIME structure or the Unix "struct tm" with a few |
| 574 | // additions and changes to prevent errors. |
| 575 | struct BASE_EXPORT Exploded { |
| 576 | int year; // Four digit year "2007" |
| 577 | int month; // 1-based month (values 1 = January, etc.) |
| 578 | int day_of_week; // 0-based day of week (0 = Sunday, etc.) |
| 579 | int day_of_month; // 1-based day of month (1-31) |
| 580 | int hour; // Hour within the current day (0-23) |
| 581 | int minute; // Minute within the current hour (0-59) |
| 582 | int second; // Second within the current minute (0-59 plus leap |
| 583 | // seconds which may take it up to 60). |
| 584 | int millisecond; // Milliseconds within the current second (0-999) |
| 585 |
| 586 | // A cursory test for whether the data members are within their |
| 587 | // respective ranges. A 'true' return value does not guarantee the |
| 588 | // Exploded value can be successfully converted to a Time value. |
| 589 | bool HasValidValues() const; |
| 590 | }; |
| 591 |
| 592 | // Contains the NULL time. Use Time::Now() to get the current time. |
| 593 | constexpr Time() : TimeBase(0) {} |
| 594 |
| 595 | // Returns the time for epoch in Unix-like system (Jan 1, 1970). |
| 596 | static Time UnixEpoch(); |
| 597 |
| 598 | // Returns the current time. Watch out, the system might adjust its clock |
| 599 | // in which case time will actually go backwards. We don't guarantee that |
| 600 | // times are increasing, or that two calls to Now() won't be the same. |
| 601 | static Time Now(); |
| 602 |
| 603 | // Returns the current time. Same as Now() except that this function always |
| 604 | // uses system time so that there are no discrepancies between the returned |
| 605 | // time and system time even on virtual environments including our test bot. |
| 606 | // For timing sensitive unittests, this function should be used. |
| 607 | static Time NowFromSystemTime(); |
| 608 |
| 609 | // Converts to/from TimeDeltas relative to the Windows epoch (1601-01-01 |
| 610 | // 00:00:00 UTC). Prefer these methods for opaque serialization and |
| 611 | // deserialization of time values, e.g. |
| 612 | // |
| 613 | // // Serialization: |
| 614 | // base::Time last_updated = ...; |
| 615 | // SaveToDatabase(last_updated.ToDeltaSinceWindowsEpoch().InMicroseconds()); |
| 616 | // |
| 617 | // // Deserialization: |
| 618 | // base::Time last_updated = base::Time::FromDeltaSinceWindowsEpoch( |
| 619 | // base::TimeDelta::FromMicroseconds(LoadFromDatabase())); |
| 620 | static Time FromDeltaSinceWindowsEpoch(TimeDelta delta); |
| 621 | TimeDelta ToDeltaSinceWindowsEpoch() const; |
| 622 |
| 623 | // Converts to/from time_t in UTC and a Time class. |
| 624 | static Time FromTimeT(time_t tt); |
| 625 | time_t ToTimeT() const; |
| 626 |
| 627 | // Converts time to/from a double which is the number of seconds since epoch |
| 628 | // (Jan 1, 1970). Webkit uses this format to represent time. |
| 629 | // Because WebKit initializes double time value to 0 to indicate "not |
| 630 | // initialized", we map it to empty Time object that also means "not |
| 631 | // initialized". |
| 632 | static Time FromDoubleT(double dt); |
| 633 | double ToDoubleT() const; |
| 634 |
| 635 | #if defined(OS_POSIX) || defined(OS_FUCHSIA) |
| 636 | // Converts the timespec structure to time. MacOS X 10.8.3 (and tentatively, |
| 637 | // earlier versions) will have the |ts|'s tv_nsec component zeroed out, |
| 638 | // having a 1 second resolution, which agrees with |
| 639 | // https://developer.apple.com/legacy/library/#technotes/tn/tn1150.html#HFSPlusDates. |
| 640 | static Time FromTimeSpec(const timespec& ts); |
| 641 | #endif |
| 642 |
| 643 | // Converts to/from the Javascript convention for times, a number of |
| 644 | // milliseconds since the epoch: |
| 645 | // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getTime. |
| 646 | // |
| 647 | // Don't use ToJsTime() in new code, since it contains a subtle hack (only |
| 648 | // exactly 1601-01-01 00:00 UTC is represented as 1970-01-01 00:00 UTC), and |
| 649 | // that is not appropriate for general use. Try to use ToJsTimeIgnoringNull() |
| 650 | // unless you have a very good reason to use ToJsTime(). |
| 651 | static Time FromJsTime(double ms_since_epoch); |
| 652 | double ToJsTime() const; |
| 653 | double ToJsTimeIgnoringNull() const; |
| 654 |
| 655 | // Converts to/from Java convention for times, a number of milliseconds since |
| 656 | // the epoch. Because the Java format has less resolution, converting to Java |
| 657 | // time is a lossy operation. |
| 658 | static Time FromJavaTime(int64_t ms_since_epoch); |
| 659 | int64_t ToJavaTime() const; |
| 660 |
| 661 | #if defined(OS_POSIX) || defined(OS_FUCHSIA) |
| 662 | static Time FromTimeVal(struct timeval t); |
| 663 | struct timeval ToTimeVal() const; |
| 664 | #endif |
| 665 |
| 666 | #if defined(OS_FUCHSIA) |
| 667 | static Time FromZxTime(zx_time_t time); |
| 668 | zx_time_t ToZxTime() const; |
| 669 | #endif |
| 670 |
| 671 | #if defined(OS_MACOSX) |
| 672 | static Time FromCFAbsoluteTime(CFAbsoluteTime t); |
| 673 | CFAbsoluteTime ToCFAbsoluteTime() const; |
| 674 | #endif |
| 675 |
| 676 | #if defined(OS_WIN) |
| 677 | static Time FromFileTime(FILETIME ft); |
| 678 | FILETIME ToFileTime() const; |
| 679 |
| 680 | // The minimum time of a low resolution timer. This is basically a windows |
| 681 | // constant of ~15.6ms. While it does vary on some older OS versions, we'll |
| 682 | // treat it as static across all windows versions. |
| 683 | static const int kMinLowResolutionThresholdMs = 16; |
| 684 |
| 685 | // Enable or disable Windows high resolution timer. |
| 686 | static void EnableHighResolutionTimer(bool enable); |
| 687 |
| 688 | // Read the minimum timer interval from the feature list. This should be |
| 689 | // called once after the feature list is initialized. This is needed for |
| 690 | // an experiment - see https://crbug.com/927165 |
| 691 | static void ReadMinTimerIntervalLowResMs(); |
| 692 |
| 693 | // Activates or deactivates the high resolution timer based on the |activate| |
| 694 | // flag. If the HighResolutionTimer is not Enabled (see |
| 695 | // EnableHighResolutionTimer), this function will return false. Otherwise |
| 696 | // returns true. Each successful activate call must be paired with a |
| 697 | // subsequent deactivate call. |
| 698 | // All callers to activate the high resolution timer must eventually call |
| 699 | // this function to deactivate the high resolution timer. |
| 700 | static bool ActivateHighResolutionTimer(bool activate); |
| 701 |
| 702 | // Returns true if the high resolution timer is both enabled and activated. |
| 703 | // This is provided for testing only, and is not tracked in a thread-safe |
| 704 | // way. |
| 705 | static bool IsHighResolutionTimerInUse(); |
| 706 |
| 707 | // The following two functions are used to report the fraction of elapsed time |
| 708 | // that the high resolution timer is activated. |
| 709 | // ResetHighResolutionTimerUsage() resets the cumulative usage and starts the |
| 710 | // measurement interval and GetHighResolutionTimerUsage() returns the |
| 711 | // percentage of time since the reset that the high resolution timer was |
| 712 | // activated. |
| 713 | // ResetHighResolutionTimerUsage() must be called at least once before calling |
| 714 | // GetHighResolutionTimerUsage(); otherwise the usage result would be |
| 715 | // undefined. |
| 716 | static void ResetHighResolutionTimerUsage(); |
| 717 | static double GetHighResolutionTimerUsage(); |
| 718 | #endif // defined(OS_WIN) |
| 719 |
| 720 | // Converts an exploded structure representing either the local time or UTC |
| 721 | // into a Time class. Returns false on a failure when, for example, a day of |
| 722 | // month is set to 31 on a 28-30 day month. Returns Time(0) on overflow. |
| 723 | static bool FromUTCExploded(const Exploded& exploded, |
| 724 | Time* time) WARN_UNUSED_RESULT { |
| 725 | return FromExploded(false, exploded, time); |
| 726 | } |
| 727 | static bool FromLocalExploded(const Exploded& exploded, |
| 728 | Time* time) WARN_UNUSED_RESULT { |
| 729 | return FromExploded(true, exploded, time); |
| 730 | } |
| 731 |
| 732 | // Converts a string representation of time to a Time object. |
| 733 | // An example of a time string which is converted is as below:- |
| 734 | // "Tue, 15 Nov 1994 12:45:26 GMT". If the timezone is not specified |
| 735 | // in the input string, FromString assumes local time and FromUTCString |
| 736 | // assumes UTC. A timezone that cannot be parsed (e.g. "UTC" which is not |
| 737 | // specified in RFC822) is treated as if the timezone is not specified. |
| 738 | // |
| 739 | // WARNING: the underlying converter is very permissive. For example: it is |
| 740 | // not checked whether a given day of the week matches the date; Feb 29 |
| 741 | // silently becomes Mar 1 in non-leap years; under certain conditions, whole |
| 742 | // English sentences may be parsed successfully and yield unexpected results. |
| 743 | // |
| 744 | // TODO(iyengar) Move the FromString/FromTimeT/ToTimeT/FromFileTime to |
| 745 | // a new time converter class. |
| 746 | static bool FromString(const char* time_string, |
| 747 | Time* parsed_time) WARN_UNUSED_RESULT { |
| 748 | return FromStringInternal(time_string, true, parsed_time); |
| 749 | } |
| 750 | static bool FromUTCString(const char* time_string, |
| 751 | Time* parsed_time) WARN_UNUSED_RESULT { |
| 752 | return FromStringInternal(time_string, false, parsed_time); |
| 753 | } |
| 754 |
| 755 | // Fills the given exploded structure with either the local time or UTC from |
| 756 | // this time structure (containing UTC). |
| 757 | void UTCExplode(Exploded* exploded) const { |
| 758 | return Explode(false, exploded); |
| 759 | } |
| 760 | void LocalExplode(Exploded* exploded) const { |
| 761 | return Explode(true, exploded); |
| 762 | } |
| 763 |
| 764 | // The following two functions round down the time to the nearest day in |
| 765 | // either UTC or local time. It will represent midnight on that day. |
| 766 | Time UTCMidnight() const { return Midnight(false); } |
| 767 | Time LocalMidnight() const { return Midnight(true); } |
| 768 |
| 769 | // Converts an integer value representing Time to a class. This may be used |
| 770 | // when deserializing a |Time| structure, using a value known to be |
| 771 | // compatible. It is not provided as a constructor because the integer type |
| 772 | // may be unclear from the perspective of a caller. |
| 773 | // |
| 774 | // DEPRECATED - Do not use in new code. For deserializing Time values, prefer |
| 775 | // Time::FromDeltaSinceWindowsEpoch(). http://crbug.com/634507 |
| 776 | static constexpr Time FromInternalValue(int64_t us) { return Time(us); } |
| 777 |
| 778 | private: |
| 779 | friend class time_internal::TimeBase<Time>; |
| 780 |
| 781 | constexpr explicit Time(int64_t microseconds_since_win_epoch) |
| 782 | : TimeBase(microseconds_since_win_epoch) {} |
| 783 |
| 784 | // Explodes the given time to either local time |is_local = true| or UTC |
| 785 | // |is_local = false|. |
| 786 | void Explode(bool is_local, Exploded* exploded) const; |
| 787 |
| 788 | // Unexplodes a given time assuming the source is either local time |
| 789 | // |is_local = true| or UTC |is_local = false|. Function returns false on |
| 790 | // failure and sets |time| to Time(0). Otherwise returns true and sets |time| |
| 791 | // to non-exploded time. |
| 792 | static bool FromExploded(bool is_local, |
| 793 | const Exploded& exploded, |
| 794 | Time* time) WARN_UNUSED_RESULT; |
| 795 |
| 796 | // Rounds down the time to the nearest day in either local time |
| 797 | // |is_local = true| or UTC |is_local = false|. |
| 798 | Time Midnight(bool is_local) const; |
| 799 |
| 800 | // Converts a string representation of time to a Time object. |
| 801 | // An example of a time string which is converted is as below:- |
| 802 | // "Tue, 15 Nov 1994 12:45:26 GMT". If the timezone is not specified |
| 803 | // in the input string, local time |is_local = true| or |
| 804 | // UTC |is_local = false| is assumed. A timezone that cannot be parsed |
| 805 | // (e.g. "UTC" which is not specified in RFC822) is treated as if the |
| 806 | // timezone is not specified. |
| 807 | static bool FromStringInternal(const char* time_string, |
| 808 | bool is_local, |
| 809 | Time* parsed_time) WARN_UNUSED_RESULT; |
| 810 |
| 811 | // Comparison does not consider |day_of_week| when doing the operation. |
| 812 | static bool ExplodedMostlyEquals(const Exploded& lhs, |
| 813 | const Exploded& rhs) WARN_UNUSED_RESULT; |
| 814 |
| 815 | // Converts the provided time in milliseconds since the Unix epoch (1970) to a |
| 816 | // Time object, avoiding overflows. |
| 817 | static bool FromMillisecondsSinceUnixEpoch(int64_t unix_milliseconds, |
| 818 | Time* time) WARN_UNUSED_RESULT; |
| 819 |
| 820 | // Returns the milliseconds since the Unix epoch (1970), rounding the |
| 821 | // microseconds towards -infinity. |
| 822 | int64_t ToRoundedDownMillisecondsSinceUnixEpoch() const; |
| 823 | }; |
| 824 |
| 825 | // static |
| 826 | constexpr TimeDelta TimeDelta::FromDays(int days) { |
| 827 | return days == std::numeric_limits<int>::max() |
| 828 | ? Max() |
| 829 | : TimeDelta(days * Time::kMicrosecondsPerDay); |
| 830 | } |
| 831 |
| 832 | // static |
| 833 | constexpr TimeDelta TimeDelta::FromHours(int hours) { |
| 834 | return hours == std::numeric_limits<int>::max() |
| 835 | ? Max() |
| 836 | : TimeDelta(hours * Time::kMicrosecondsPerHour); |
| 837 | } |
| 838 |
| 839 | // static |
| 840 | constexpr TimeDelta TimeDelta::FromMinutes(int minutes) { |
| 841 | return minutes == std::numeric_limits<int>::max() |
| 842 | ? Max() |
| 843 | : TimeDelta(minutes * Time::kMicrosecondsPerMinute); |
| 844 | } |
| 845 |
| 846 | // static |
| 847 | constexpr TimeDelta TimeDelta::FromSeconds(int64_t secs) { |
| 848 | return FromProduct(secs, Time::kMicrosecondsPerSecond); |
| 849 | } |
| 850 |
| 851 | // static |
| 852 | constexpr TimeDelta TimeDelta::FromMilliseconds(int64_t ms) { |
| 853 | return FromProduct(ms, Time::kMicrosecondsPerMillisecond); |
| 854 | } |
| 855 |
| 856 | // static |
| 857 | constexpr TimeDelta TimeDelta::FromMicroseconds(int64_t us) { |
| 858 | return TimeDelta(us); |
| 859 | } |
| 860 |
| 861 | // static |
| 862 | constexpr TimeDelta TimeDelta::FromNanoseconds(int64_t ns) { |
| 863 | return TimeDelta(ns / Time::kNanosecondsPerMicrosecond); |
| 864 | } |
| 865 |
| 866 | // static |
| 867 | constexpr TimeDelta TimeDelta::FromSecondsD(double secs) { |
| 868 | return FromDouble(secs * Time::kMicrosecondsPerSecond); |
| 869 | } |
| 870 |
| 871 | // static |
| 872 | constexpr TimeDelta TimeDelta::FromMillisecondsD(double ms) { |
| 873 | return FromDouble(ms * Time::kMicrosecondsPerMillisecond); |
| 874 | } |
| 875 |
| 876 | // static |
| 877 | constexpr TimeDelta TimeDelta::FromMicrosecondsD(double us) { |
| 878 | return FromDouble(us); |
| 879 | } |
| 880 |
| 881 | // static |
| 882 | constexpr TimeDelta TimeDelta::FromNanosecondsD(double ns) { |
| 883 | return FromDouble(ns / Time::kNanosecondsPerMicrosecond); |
| 884 | } |
| 885 |
| 886 | // static |
| 887 | constexpr TimeDelta TimeDelta::Max() { |
| 888 | return TimeDelta(std::numeric_limits<int64_t>::max()); |
| 889 | } |
| 890 |
| 891 | // static |
| 892 | constexpr TimeDelta TimeDelta::Min() { |
| 893 | return TimeDelta(std::numeric_limits<int64_t>::min()); |
| 894 | } |
| 895 |
| 896 | // static |
| 897 | constexpr TimeDelta TimeDelta::FromDouble(double value) { |
| 898 | return TimeDelta(saturated_cast<int64_t>(value)); |
| 899 | } |
| 900 |
| 901 | // static |
| 902 | constexpr TimeDelta TimeDelta::FromProduct(int64_t value, |
| 903 | int64_t positive_value) { |
| 904 | DCHECK(positive_value > 0); // NOLINT, DCHECK_GT isn't constexpr. |
| 905 | return value > std::numeric_limits<int64_t>::max() / positive_value |
| 906 | ? Max() |
| 907 | : value < std::numeric_limits<int64_t>::min() / positive_value |
| 908 | ? Min() |
| 909 | : TimeDelta(value * positive_value); |
| 910 | } |
| 911 |
| 912 | // For logging use only. |
| 913 | BASE_EXPORT std::ostream& operator<<(std::ostream& os, Time time); |
| 914 |
| 915 | // TimeTicks ------------------------------------------------------------------ |
| 916 |
| 917 | // Represents monotonically non-decreasing clock time. |
| 918 | class BASE_EXPORT TimeTicks : public time_internal::TimeBase<TimeTicks> { |
| 919 | public: |
| 920 | // The underlying clock used to generate new TimeTicks. |
| 921 | enum class Clock { |
| 922 | FUCHSIA_ZX_CLOCK_MONOTONIC, |
| 923 | LINUX_CLOCK_MONOTONIC, |
| 924 | IOS_CF_ABSOLUTE_TIME_MINUS_KERN_BOOTTIME, |
| 925 | MAC_MACH_ABSOLUTE_TIME, |
| 926 | WIN_QPC, |
| 927 | WIN_ROLLOVER_PROTECTED_TIME_GET_TIME |
| 928 | }; |
| 929 |
| 930 | constexpr TimeTicks() : TimeBase(0) {} |
| 931 |
| 932 | // Platform-dependent tick count representing "right now." When |
| 933 | // IsHighResolution() returns false, the resolution of the clock could be |
| 934 | // as coarse as ~15.6ms. Otherwise, the resolution should be no worse than one |
| 935 | // microsecond. |
| 936 | static TimeTicks Now(); |
| 937 |
| 938 | // Returns true if the high resolution clock is working on this system and |
| 939 | // Now() will return high resolution values. Note that, on systems where the |
| 940 | // high resolution clock works but is deemed inefficient, the low resolution |
| 941 | // clock will be used instead. |
| 942 | static bool IsHighResolution() WARN_UNUSED_RESULT; |
| 943 |
| 944 | // Returns true if TimeTicks is consistent across processes, meaning that |
| 945 | // timestamps taken on different processes can be safely compared with one |
| 946 | // another. (Note that, even on platforms where this returns true, time values |
| 947 | // from different threads that are within one tick of each other must be |
| 948 | // considered to have an ambiguous ordering.) |
| 949 | static bool IsConsistentAcrossProcesses() WARN_UNUSED_RESULT; |
| 950 |
| 951 | #if defined(OS_FUCHSIA) |
| 952 | // Converts between TimeTicks and an ZX_CLOCK_MONOTONIC zx_time_t value. |
| 953 | static TimeTicks FromZxTime(zx_time_t nanos_since_boot); |
| 954 | zx_time_t ToZxTime() const; |
| 955 | #endif |
| 956 |
| 957 | #if defined(OS_WIN) |
| 958 | // Translates an absolute QPC timestamp into a TimeTicks value. The returned |
| 959 | // value has the same origin as Now(). Do NOT attempt to use this if |
| 960 | // IsHighResolution() returns false. |
| 961 | static TimeTicks FromQPCValue(LONGLONG qpc_value); |
| 962 | #endif |
| 963 |
| 964 | #if defined(OS_MACOSX) && !defined(OS_IOS) |
| 965 | static TimeTicks FromMachAbsoluteTime(uint64_t mach_absolute_time); |
| 966 | #endif // defined(OS_MACOSX) && !defined(OS_IOS) |
| 967 |
| 968 | #if defined(OS_ANDROID) || defined(OS_CHROMEOS) |
| 969 | // Converts to TimeTicks the value obtained from SystemClock.uptimeMillis(). |
| 970 | // Note: this convertion may be non-monotonic in relation to previously |
| 971 | // obtained TimeTicks::Now() values because of the truncation (to |
| 972 | // milliseconds) performed by uptimeMillis(). |
| 973 | static TimeTicks FromUptimeMillis(int64_t uptime_millis_value); |
| 974 | #endif |
| 975 |
| 976 | // Get an estimate of the TimeTick value at the time of the UnixEpoch. Because |
| 977 | // Time and TimeTicks respond differently to user-set time and NTP |
| 978 | // adjustments, this number is only an estimate. Nevertheless, this can be |
| 979 | // useful when you need to relate the value of TimeTicks to a real time and |
| 980 | // date. Note: Upon first invocation, this function takes a snapshot of the |
| 981 | // realtime clock to establish a reference point. This function will return |
| 982 | // the same value for the duration of the application, but will be different |
| 983 | // in future application runs. |
| 984 | static TimeTicks UnixEpoch(); |
| 985 |
| 986 | // Returns |this| snapped to the next tick, given a |tick_phase| and |
| 987 | // repeating |tick_interval| in both directions. |this| may be before, |
| 988 | // after, or equal to the |tick_phase|. |
| 989 | TimeTicks SnappedToNextTick(TimeTicks tick_phase, |
| 990 | TimeDelta tick_interval) const; |
| 991 |
| 992 | // Returns an enum indicating the underlying clock being used to generate |
| 993 | // TimeTicks timestamps. This function should only be used for debugging and |
| 994 | // logging purposes. |
| 995 | static Clock GetClock(); |
| 996 |
| 997 | // Converts an integer value representing TimeTicks to a class. This may be |
| 998 | // used when deserializing a |TimeTicks| structure, using a value known to be |
| 999 | // compatible. It is not provided as a constructor because the integer type |
| 1000 | // may be unclear from the perspective of a caller. |
| 1001 | // |
| 1002 | // DEPRECATED - Do not use in new code. For deserializing TimeTicks values, |
| 1003 | // prefer TimeTicks + TimeDelta(). http://crbug.com/634507 |
| 1004 | static constexpr TimeTicks FromInternalValue(int64_t us) { |
| 1005 | return TimeTicks(us); |
| 1006 | } |
| 1007 |
| 1008 | protected: |
| 1009 | #if defined(OS_WIN) |
| 1010 | typedef DWORD (*TickFunctionType)(void); |
| 1011 | static TickFunctionType SetMockTickFunction(TickFunctionType ticker); |
| 1012 | #endif |
| 1013 |
| 1014 | private: |
| 1015 | friend class time_internal::TimeBase<TimeTicks>; |
| 1016 |
| 1017 | // Please use Now() to create a new object. This is for internal use |
| 1018 | // and testing. |
| 1019 | constexpr explicit TimeTicks(int64_t us) : TimeBase(us) {} |
| 1020 | }; |
| 1021 |
| 1022 | // For logging use only. |
| 1023 | BASE_EXPORT std::ostream& operator<<(std::ostream& os, TimeTicks time_ticks); |
| 1024 |
| 1025 | // ThreadTicks ---------------------------------------------------------------- |
| 1026 |
| 1027 | // Represents a clock, specific to a particular thread, than runs only while the |
| 1028 | // thread is running. |
| 1029 | class BASE_EXPORT ThreadTicks : public time_internal::TimeBase<ThreadTicks> { |
| 1030 | public: |
| 1031 | constexpr ThreadTicks() : TimeBase(0) {} |
| 1032 |
| 1033 | // Returns true if ThreadTicks::Now() is supported on this system. |
| 1034 | static bool IsSupported() WARN_UNUSED_RESULT { |
| 1035 | #if (defined(_POSIX_THREAD_CPUTIME) && (_POSIX_THREAD_CPUTIME >= 0)) || \ |
| 1036 | (defined(OS_MACOSX) && !defined(OS_IOS)) || defined(OS_ANDROID) || \ |
| 1037 | defined(OS_FUCHSIA) |
| 1038 | return true; |
| 1039 | #elif defined(OS_WIN) |
| 1040 | return IsSupportedWin(); |
| 1041 | #else |
| 1042 | return false; |
| 1043 | #endif |
| 1044 | } |
| 1045 |
| 1046 | // Waits until the initialization is completed. Needs to be guarded with a |
| 1047 | // call to IsSupported(). |
| 1048 | static void WaitUntilInitialized() { |
| 1049 | #if defined(OS_WIN) |
| 1050 | WaitUntilInitializedWin(); |
| 1051 | #endif |
| 1052 | } |
| 1053 |
| 1054 | // Returns thread-specific CPU-time on systems that support this feature. |
| 1055 | // Needs to be guarded with a call to IsSupported(). Use this timer |
| 1056 | // to (approximately) measure how much time the calling thread spent doing |
| 1057 | // actual work vs. being de-scheduled. May return bogus results if the thread |
| 1058 | // migrates to another CPU between two calls. Returns an empty ThreadTicks |
| 1059 | // object until the initialization is completed. If a clock reading is |
| 1060 | // absolutely needed, call WaitUntilInitialized() before this method. |
| 1061 | static ThreadTicks Now(); |
| 1062 |
| 1063 | #if defined(OS_WIN) |
| 1064 | // Similar to Now() above except this returns thread-specific CPU time for an |
| 1065 | // arbitrary thread. All comments for Now() method above apply apply to this |
| 1066 | // method as well. |
| 1067 | static ThreadTicks GetForThread(const PlatformThreadHandle& thread_handle); |
| 1068 | #endif |
| 1069 |
| 1070 | // Converts an integer value representing ThreadTicks to a class. This may be |
| 1071 | // used when deserializing a |ThreadTicks| structure, using a value known to |
| 1072 | // be compatible. It is not provided as a constructor because the integer type |
| 1073 | // may be unclear from the perspective of a caller. |
| 1074 | // |
| 1075 | // DEPRECATED - Do not use in new code. For deserializing ThreadTicks values, |
| 1076 | // prefer ThreadTicks + TimeDelta(). http://crbug.com/634507 |
| 1077 | static constexpr ThreadTicks FromInternalValue(int64_t us) { |
| 1078 | return ThreadTicks(us); |
| 1079 | } |
| 1080 |
| 1081 | private: |
| 1082 | friend class time_internal::TimeBase<ThreadTicks>; |
| 1083 |
| 1084 | // Please use Now() or GetForThread() to create a new object. This is for |
| 1085 | // internal use and testing. |
| 1086 | constexpr explicit ThreadTicks(int64_t us) : TimeBase(us) {} |
| 1087 |
| 1088 | #if defined(OS_WIN) |
| 1089 | FRIEND_TEST_ALL_PREFIXES(TimeTicks, TSCTicksPerSecond); |
| 1090 |
| 1091 | #if defined(ARCH_CPU_ARM64) |
| 1092 | // TSCTicksPerSecond is not supported on Windows on Arm systems because the |
| 1093 | // cycle-counting methods use the actual CPU cycle count, and not a consistent |
| 1094 | // incrementing counter. |
| 1095 | #else |
| 1096 | // Returns the frequency of the TSC in ticks per second, or 0 if it hasn't |
| 1097 | // been measured yet. Needs to be guarded with a call to IsSupported(). |
| 1098 | // This method is declared here rather than in the anonymous namespace to |
| 1099 | // allow testing. |
| 1100 | static double TSCTicksPerSecond(); |
| 1101 | #endif |
| 1102 |
| 1103 | static bool IsSupportedWin() WARN_UNUSED_RESULT; |
| 1104 | static void WaitUntilInitializedWin(); |
| 1105 | #endif |
| 1106 | }; |
| 1107 |
| 1108 | // For logging use only. |
| 1109 | BASE_EXPORT std::ostream& operator<<(std::ostream& os, ThreadTicks time_ticks); |
| 1110 |
| 1111 | } // namespace base |
| 1112 |
| 1113 | #endif // BASE_TIME_TIME_H_ |
| 1114 |