time.h 17.2 KB
Newer Older
1
// Copyright 2013 the V8 project authors. All rights reserved.
2 3
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
4

5 6
#ifndef V8_BASE_PLATFORM_TIME_H_
#define V8_BASE_PLATFORM_TIME_H_
7

8 9
#include <stdint.h>

10 11
#include <ctime>
#include <iosfwd>
12 13
#include <limits>

14
#include "src/base/base-export.h"
15
#include "src/base/bits.h"
16
#include "src/base/macros.h"
17
#include "src/base/safe_conversions.h"
18 19 20
#if V8_OS_WIN
#include "src/base/win32-headers.h"
#endif
21 22 23 24

// Forward declarations.
extern "C" {
struct _FILETIME;
25 26
struct mach_timespec;
struct timespec;
27 28 29 30
struct timeval;
}

namespace v8 {
31
namespace base {
32 33

class Time;
34
class TimeDelta;
35 36
class TimeTicks;

37 38 39
namespace time_internal {
template<class TimeClass>
class TimeBase;
40
}  // namespace time_internal
41

42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
class TimeConstants {
 public:
  static constexpr int64_t kHoursPerDay = 24;
  static constexpr int64_t kMillisecondsPerSecond = 1000;
  static constexpr int64_t kMillisecondsPerDay =
      kMillisecondsPerSecond * 60 * 60 * kHoursPerDay;
  static constexpr int64_t kMicrosecondsPerMillisecond = 1000;
  static constexpr int64_t kMicrosecondsPerSecond =
      kMicrosecondsPerMillisecond * kMillisecondsPerSecond;
  static constexpr int64_t kMicrosecondsPerMinute = kMicrosecondsPerSecond * 60;
  static constexpr int64_t kMicrosecondsPerHour = kMicrosecondsPerMinute * 60;
  static constexpr int64_t kMicrosecondsPerDay =
      kMicrosecondsPerHour * kHoursPerDay;
  static constexpr int64_t kMicrosecondsPerWeek = kMicrosecondsPerDay * 7;
  static constexpr int64_t kNanosecondsPerMicrosecond = 1000;
  static constexpr int64_t kNanosecondsPerSecond =
      kNanosecondsPerMicrosecond * kMicrosecondsPerSecond;
};

61 62 63 64 65 66
// -----------------------------------------------------------------------------
// TimeDelta
//
// This class represents a duration of time, internally represented in
// microseonds.

67
class V8_BASE_EXPORT TimeDelta final {
68
 public:
69
  constexpr TimeDelta() : delta_(0) {}
70 71

  // Converts units of time to TimeDeltas.
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
  static constexpr TimeDelta FromDays(int days) {
    return TimeDelta(days * TimeConstants::kMicrosecondsPerDay);
  }
  static constexpr TimeDelta FromHours(int hours) {
    return TimeDelta(hours * TimeConstants::kMicrosecondsPerHour);
  }
  static constexpr TimeDelta FromMinutes(int minutes) {
    return TimeDelta(minutes * TimeConstants::kMicrosecondsPerMinute);
  }
  static constexpr TimeDelta FromSeconds(int64_t seconds) {
    return TimeDelta(seconds * TimeConstants::kMicrosecondsPerSecond);
  }
  static constexpr TimeDelta FromMilliseconds(int64_t milliseconds) {
    return TimeDelta(milliseconds * TimeConstants::kMicrosecondsPerMillisecond);
  }
  static constexpr TimeDelta FromMicroseconds(int64_t microseconds) {
88 89
    return TimeDelta(microseconds);
  }
90 91 92
  static constexpr TimeDelta FromNanoseconds(int64_t nanoseconds) {
    return TimeDelta(nanoseconds / TimeConstants::kNanosecondsPerMicrosecond);
  }
93

94 95 96
  static TimeDelta FromSecondsD(double seconds) {
    return FromDouble(seconds * TimeConstants::kMicrosecondsPerSecond);
  }
97 98 99 100 101
  static TimeDelta FromMillisecondsD(double milliseconds) {
    return FromDouble(milliseconds *
                      TimeConstants::kMicrosecondsPerMillisecond);
  }

102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
  // Returns the maximum time delta, which should be greater than any reasonable
  // time delta we might compare it to. Adding or subtracting the maximum time
  // delta to a time or another time delta has an undefined result.
  static constexpr TimeDelta Max();

  // Returns the minimum time delta, which should be less than than any
  // reasonable time delta we might compare it to. Adding or subtracting the
  // minimum time delta to a time or another time delta has an undefined result.
  static constexpr TimeDelta Min();

  // Returns true if the time delta is zero.
  constexpr bool IsZero() const { return delta_ == 0; }

  // Returns true if the time delta is the maximum/minimum time delta.
  constexpr bool IsMax() const {
    return delta_ == std::numeric_limits<int64_t>::max();
  }
  constexpr bool IsMin() const {
    return delta_ == std::numeric_limits<int64_t>::min();
  }

123 124 125 126 127 128 129 130 131 132 133 134 135
  // Returns the time delta in some unit. The F versions return a floating
  // point value, the "regular" versions return a rounded-down value.
  //
  // InMillisecondsRoundedUp() instead returns an integer that is rounded up
  // to the next full millisecond.
  int InDays() const;
  int InHours() const;
  int InMinutes() const;
  double InSecondsF() const;
  int64_t InSeconds() const;
  double InMillisecondsF() const;
  int64_t InMilliseconds() const;
  int64_t InMillisecondsRoundedUp() const;
136
  int64_t InMicroseconds() const;
137 138
  int64_t InNanoseconds() const;

139 140 141 142
  // Converts to/from Mach time specs.
  static TimeDelta FromMachTimespec(struct mach_timespec ts);
  struct mach_timespec ToMachTimespec() const;

143 144 145 146
  // Converts to/from POSIX time specs.
  static TimeDelta FromTimespec(struct timespec ts);
  struct timespec ToTimespec() const;

147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
  // Computations with other deltas.
  TimeDelta operator+(const TimeDelta& other) const {
    return TimeDelta(delta_ + other.delta_);
  }
  TimeDelta operator-(const TimeDelta& other) const {
    return TimeDelta(delta_ - other.delta_);
  }

  TimeDelta& operator+=(const TimeDelta& other) {
    delta_ += other.delta_;
    return *this;
  }
  TimeDelta& operator-=(const TimeDelta& other) {
    delta_ -= other.delta_;
    return *this;
  }
163
  constexpr TimeDelta operator-() const { return TimeDelta(-delta_); }
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192

  double TimesOf(const TimeDelta& other) const {
    return static_cast<double>(delta_) / static_cast<double>(other.delta_);
  }
  double PercentOf(const TimeDelta& other) const {
    return TimesOf(other) * 100.0;
  }

  // Computations with ints, note that we only allow multiplicative operations
  // with ints, and additive operations with other deltas.
  TimeDelta operator*(int64_t a) const {
    return TimeDelta(delta_ * a);
  }
  TimeDelta operator/(int64_t a) const {
    return TimeDelta(delta_ / a);
  }
  TimeDelta& operator*=(int64_t a) {
    delta_ *= a;
    return *this;
  }
  TimeDelta& operator/=(int64_t a) {
    delta_ /= a;
    return *this;
  }
  int64_t operator/(const TimeDelta& other) const {
    return delta_ / other.delta_;
  }

  // Comparison operators.
193
  constexpr bool operator==(const TimeDelta& other) const {
194 195
    return delta_ == other.delta_;
  }
196
  constexpr bool operator!=(const TimeDelta& other) const {
197 198
    return delta_ != other.delta_;
  }
199
  constexpr bool operator<(const TimeDelta& other) const {
200 201
    return delta_ < other.delta_;
  }
202
  constexpr bool operator<=(const TimeDelta& other) const {
203 204
    return delta_ <= other.delta_;
  }
205
  constexpr bool operator>(const TimeDelta& other) const {
206 207
    return delta_ > other.delta_;
  }
208
  constexpr bool operator>=(const TimeDelta& other) const {
209 210 211 212
    return delta_ >= other.delta_;
  }

 private:
213 214 215
  // TODO(v8:10620): constexpr requires constexpr saturated_cast.
  static inline TimeDelta FromDouble(double value);

216
  template<class TimeClass> friend class time_internal::TimeBase;
217 218 219
  // Constructs a delta given the duration in microseconds. This is private
  // to avoid confusion by callers with an integer constructor. Use
  // FromSeconds, FromMilliseconds, etc. instead.
220
  explicit constexpr TimeDelta(int64_t delta) : delta_(delta) {}
221 222 223 224 225

  // Delta in microseconds.
  int64_t delta_;
};

226 227 228 229 230
// static
TimeDelta TimeDelta::FromDouble(double value) {
  return TimeDelta(saturated_cast<int64_t>(value));
}

231 232 233 234 235 236 237 238 239
// static
constexpr TimeDelta TimeDelta::Max() {
  return TimeDelta(std::numeric_limits<int64_t>::max());
}

// static
constexpr TimeDelta TimeDelta::Min() {
  return TimeDelta(std::numeric_limits<int64_t>::min());
}
240

241 242 243
namespace time_internal {

// TimeBase--------------------------------------------------------------------
244

245 246 247 248
// Provides value storage and comparison/math operations common to all time
// classes. Each subclass provides for strong type-checking to ensure
// semantically meaningful comparison/math of time values from the same clock
// source or timeline.
249 250
template <class TimeClass>
class TimeBase : public TimeConstants {
251
 public:
252 253 254 255 256 257 258
#if V8_OS_WIN
  // To avoid overflow in QPC to Microseconds calculations, since we multiply
  // by kMicrosecondsPerSecond, then the QPC value should not exceed
  // (2^63 - 1) / 1E6. If it exceeds that threshold, we divide then multiply.
  static constexpr int64_t kQPCOverflowThreshold = INT64_C(0x8637BD05AF7);
#endif

259 260 261 262 263
  // Returns true if this object has not been initialized.
  //
  // Warning: Be careful when writing code that performs math on time values,
  // since it's possible to produce a valid "zero" result that should not be
  // interpreted as a "null" value.
264 265 266 267 268 269 270 271 272
  constexpr bool IsNull() const { return us_ == 0; }

  // Returns the maximum/minimum times, which should be greater/less than any
  // reasonable time with which we might compare it.
  static TimeClass Max() {
    return TimeClass(std::numeric_limits<int64_t>::max());
  }
  static TimeClass Min() {
    return TimeClass(std::numeric_limits<int64_t>::min());
273
  }
274

275 276 277 278 279 280 281
  // Returns true if this object represents the maximum/minimum time.
  constexpr bool IsMax() const {
    return us_ == std::numeric_limits<int64_t>::max();
  }
  constexpr bool IsMin() const {
    return us_ == std::numeric_limits<int64_t>::min();
  }
282

283 284 285 286 287
  // For serializing only. Use FromInternalValue() to reconstitute. Please don't
  // use this and do arithmetic on it, as it is more error prone than using the
  // provided operators.
  int64_t ToInternalValue() const { return us_; }

288 289 290 291 292 293 294 295 296 297
  // The amount of time since the origin (or "zero") point. This is a syntactic
  // convenience to aid in code readability, mainly for debugging/testing use
  // cases.
  //
  // Warning: While the Time subclass has a fixed origin point, the origin for
  // the other subclasses can vary each time the application is restarted.
  constexpr TimeDelta since_origin() const {
    return TimeDelta::FromMicroseconds(us_);
  }

298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
  TimeClass& operator=(TimeClass other) {
    us_ = other.us_;
    return *(static_cast<TimeClass*>(this));
  }

  // Compute the difference between two times.
  TimeDelta operator-(TimeClass other) const {
    return TimeDelta::FromMicroseconds(us_ - other.us_);
  }

  // Return a new time modified by some delta.
  TimeClass operator+(TimeDelta delta) const {
    return TimeClass(bits::SignedSaturatedAdd64(delta.delta_, us_));
  }
  TimeClass operator-(TimeDelta delta) const {
    return TimeClass(-bits::SignedSaturatedSub64(delta.delta_, us_));
  }

  // Modify by some time delta.
  TimeClass& operator+=(TimeDelta delta) {
    return static_cast<TimeClass&>(*this = (*this + delta));
  }
  TimeClass& operator-=(TimeDelta delta) {
    return static_cast<TimeClass&>(*this = (*this - delta));
  }

  // Comparison operators
  bool operator==(TimeClass other) const {
    return us_ == other.us_;
  }
  bool operator!=(TimeClass other) const {
    return us_ != other.us_;
  }
  bool operator<(TimeClass other) const {
    return us_ < other.us_;
  }
  bool operator<=(TimeClass other) const {
    return us_ <= other.us_;
  }
  bool operator>(TimeClass other) const {
    return us_ > other.us_;
  }
  bool operator>=(TimeClass other) const {
    return us_ >= other.us_;
  }

  // Converts an integer value representing TimeClass to a class. This is used
  // when deserializing a |TimeClass| structure, using a value known to be
  // compatible. It is not provided as a constructor because the integer type
  // may be unclear from the perspective of a caller.
  static TimeClass FromInternalValue(int64_t us) { return TimeClass(us); }

 protected:
351
  explicit constexpr TimeBase(int64_t us) : us_(us) {}
352 353 354 355 356 357 358 359 360 361 362 363 364 365

  // Time value in a microsecond timebase.
  int64_t us_;
};

}  // namespace time_internal


// -----------------------------------------------------------------------------
// Time
//
// This class represents an absolute point in time, internally represented as
// microseconds (s/1,000,000) since 00:00:00 UTC, January 1, 1970.

366
class V8_BASE_EXPORT Time final : public time_internal::TimeBase<Time> {
367
 public:
368
  // Contains the nullptr time. Use Time::Now() to get the current time.
369
  constexpr Time() : TimeBase(0) {}
370

371 372 373 374 375 376 377 378 379 380 381 382 383 384
  // Returns the current time. Watch out, the system might adjust its clock
  // in which case time will actually go backwards. We don't guarantee that
  // times are increasing, or that two calls to Now() won't be the same.
  static Time Now();

  // Returns the current time. Same as Now() except that this function always
  // uses system time so that there are no discrepancies between the returned
  // time and system time even on virtual environments including our test bot.
  // For timing sensitive unittests, this function should be used.
  static Time NowFromSystemTime();

  // Returns the time for epoch in Unix-like system (Jan 1, 1970).
  static Time UnixEpoch() { return Time(0); }

385 386 387 388
  // Converts to/from POSIX time specs.
  static Time FromTimespec(struct timespec ts);
  struct timespec ToTimespec() const;

389 390 391 392 393 394 395 396 397 398 399 400 401 402
  // Converts to/from POSIX time values.
  static Time FromTimeval(struct timeval tv);
  struct timeval ToTimeval() const;

  // Converts to/from Windows file times.
  static Time FromFiletime(struct _FILETIME ft);
  struct _FILETIME ToFiletime() const;

  // Converts to/from the Javascript convention for times, a number of
  // milliseconds since the epoch:
  static Time FromJsTime(double ms_since_epoch);
  double ToJsTime() const;

 private:
403
  friend class time_internal::TimeBase<Time>;
404
  explicit constexpr Time(int64_t us) : TimeBase(us) {}
405 406
};

407
V8_BASE_EXPORT std::ostream& operator<<(std::ostream&, const Time&);
408

409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
inline Time operator+(const TimeDelta& delta, const Time& time) {
  return time + delta;
}


// -----------------------------------------------------------------------------
// TimeTicks
//
// This class represents an abstract time that is most of the time incrementing
// for use in measuring time durations. It is internally represented in
// microseconds.  It can not be converted to a human-readable time, but is
// guaranteed not to decrease (if the user changes the computer clock,
// Time::Now() may actually decrease or jump).  But note that TimeTicks may
// "stand still", for example if the computer suspended.

424 425
class V8_BASE_EXPORT TimeTicks final
    : public time_internal::TimeBase<TimeTicks> {
426
 public:
427
  constexpr TimeTicks() : TimeBase(0) {}
428

429 430 431 432
  // Platform-dependent tick count representing "right now." When
  // IsHighResolution() returns false, the resolution of the clock could be as
  // coarse as ~15.6ms. Otherwise, the resolution should be no worse than one
  // microsecond.
433 434 435
  // This method never returns a null TimeTicks.
  static TimeTicks Now();

436 437 438
  // This is equivalent to Now() but DCHECKs that IsHighResolution(). Useful for
  // test frameworks that rely on high resolution clocks (in practice all
  // platforms but low-end Windows devices have high resolution clocks).
439 440 441
  static TimeTicks HighResolutionNow();

  // Returns true if the high-resolution clock is working on this system.
442
  static bool IsHighResolution();
443 444

 private:
445 446
  friend class time_internal::TimeBase<TimeTicks>;

447
  // Please use Now() to create a new object. This is for internal use
448
  // and testing. Ticks are in microseconds.
449
  explicit constexpr TimeTicks(int64_t ticks) : TimeBase(ticks) {}
450 451 452 453 454 455
};

inline TimeTicks operator+(const TimeDelta& delta, const TimeTicks& ticks) {
  return ticks + delta;
}

456 457 458 459 460

// ThreadTicks ----------------------------------------------------------------

// Represents a clock, specific to a particular thread, than runs only while the
// thread is running.
461 462
class V8_BASE_EXPORT ThreadTicks final
    : public time_internal::TimeBase<ThreadTicks> {
463
 public:
464
  constexpr ThreadTicks() : TimeBase(0) {}
465 466 467 468

  // Returns true if ThreadTicks::Now() is supported on this system.
  static bool IsSupported();

469 470 471 472 473 474 475 476
  // Waits until the initialization is completed. Needs to be guarded with a
  // call to IsSupported().
  static void WaitUntilInitialized() {
#if V8_OS_WIN
    WaitUntilInitializedWin();
#endif
  }

477 478 479 480 481
  // Returns thread-specific CPU-time on systems that support this feature.
  // Needs to be guarded with a call to IsSupported(). Use this timer
  // to (approximately) measure how much time the calling thread spent doing
  // actual work vs. being de-scheduled. May return bogus results if the thread
  // migrates to another CPU between two calls. Returns an empty ThreadTicks
482 483
  // object until the initialization is completed. If a clock reading is
  // absolutely needed, call WaitUntilInitialized() before this method.
484 485
  static ThreadTicks Now();

486 487 488 489 490 491 492
#if V8_OS_WIN
  // Similar to Now() above except this returns thread-specific CPU time for an
  // arbitrary thread. All comments for Now() method above apply apply to this
  // method as well.
  static ThreadTicks GetForThread(const HANDLE& thread_handle);
#endif

493
 private:
494 495 496
  template <class TimeClass>
  friend class time_internal::TimeBase;

497 498
  // Please use Now() or GetForThread() to create a new object. This is for
  // internal use and testing. Ticks are in microseconds.
499
  explicit constexpr ThreadTicks(int64_t ticks) : TimeBase(ticks) {}
500 501 502 503 504 505 506 507

#if V8_OS_WIN
  // Returns the frequency of the TSC in ticks per second, or 0 if it hasn't
  // been measured yet. Needs to be guarded with a call to IsSupported().
  static double TSCTicksPerSecond();
  static bool IsSupportedWin();
  static void WaitUntilInitializedWin();
#endif
508 509
};

510 511
}  // namespace base
}  // namespace v8
512

513
#endif  // V8_BASE_PLATFORM_TIME_H_