1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #ifndef mozilla_TimeStamp_h
8 #define mozilla_TimeStamp_h
10 #include "mozilla/Assertions.h"
11 #include "mozilla/Attributes.h"
12 #include "mozilla/FloatingPoint.h"
13 #include "mozilla/Types.h"
14 #include <algorithm> // for std::min, std::max
17 #include <type_traits>
25 // defines TimeStampValue as a complex value keeping both
26 // GetTickCount and QueryPerformanceCounter values
27 # include "TimeStamp_windows.h"
29 # include "mozilla/Maybe.h" // For TimeStamp::RawQueryPerformanceCounterValue
35 typedef uint64_t TimeStampValue
;
42 * Platform-specific implementation details of BaseTimeDuration.
44 class BaseTimeDurationPlatformUtils
{
46 static MFBT_API
double ToSeconds(int64_t aTicks
);
47 static MFBT_API
double ToSecondsSigDigits(int64_t aTicks
);
48 static MFBT_API
int64_t TicksFromMilliseconds(double aMilliseconds
);
49 static MFBT_API
int64_t ResolutionInTicks();
53 * Instances of this class represent the length of an interval of time.
54 * Negative durations are allowed, meaning the end is before the start.
56 * Internally the duration is stored as a int64_t in units of
57 * PR_TicksPerSecond() when building with NSPR interval timers, or a
58 * system-dependent unit when building with system clocks. The
59 * system-dependent unit must be constant, otherwise the semantics of
60 * this class would be broken.
62 * The ValueCalculator template parameter determines how arithmetic
63 * operations are performed on the integer count of ticks (mValue).
65 template <typename ValueCalculator
>
66 class BaseTimeDuration
{
68 // The default duration is 0.
69 constexpr BaseTimeDuration() : mValue(0) {}
70 // Allow construction using '0' as the initial value, for readability,
71 // but no other numbers (so we don't have any implicit unit conversions).
72 struct _SomethingVeryRandomHere
;
73 MOZ_IMPLICIT
BaseTimeDuration(_SomethingVeryRandomHere
* aZero
) : mValue(0) {
74 MOZ_ASSERT(!aZero
, "Who's playing funny games here?");
76 // Default copy-constructor and assignment are OK
78 // Converting copy-constructor and assignment operator
80 explicit BaseTimeDuration(const BaseTimeDuration
<E
>& aOther
)
81 : mValue(aOther
.mValue
) {}
84 BaseTimeDuration
& operator=(const BaseTimeDuration
<E
>& aOther
) {
85 mValue
= aOther
.mValue
;
89 double ToSeconds() const {
90 if (mValue
== INT64_MAX
) {
91 return PositiveInfinity
<double>();
93 if (mValue
== INT64_MIN
) {
94 return NegativeInfinity
<double>();
96 return BaseTimeDurationPlatformUtils::ToSeconds(mValue
);
98 // Return a duration value that includes digits of time we think to
99 // be significant. This method should be used when displaying a
101 double ToSecondsSigDigits() const {
102 if (mValue
== INT64_MAX
) {
103 return PositiveInfinity
<double>();
105 if (mValue
== INT64_MIN
) {
106 return NegativeInfinity
<double>();
108 return BaseTimeDurationPlatformUtils::ToSecondsSigDigits(mValue
);
110 double ToMilliseconds() const { return ToSeconds() * 1000.0; }
111 double ToMicroseconds() const { return ToMilliseconds() * 1000.0; }
113 // Using a double here is safe enough; with 53 bits we can represent
114 // durations up to over 280,000 years exactly. If the units of
115 // mValue do not allow us to represent durations of that length,
116 // long durations are clamped to the max/min representable value
117 // instead of overflowing.
118 static inline BaseTimeDuration
FromSeconds(double aSeconds
) {
119 return FromMilliseconds(aSeconds
* 1000.0);
121 static BaseTimeDuration
FromMilliseconds(double aMilliseconds
) {
122 if (aMilliseconds
== PositiveInfinity
<double>()) {
125 if (aMilliseconds
== NegativeInfinity
<double>()) {
126 return FromTicks(INT64_MIN
);
129 BaseTimeDurationPlatformUtils::TicksFromMilliseconds(aMilliseconds
));
131 static inline BaseTimeDuration
FromMicroseconds(double aMicroseconds
) {
132 return FromMilliseconds(aMicroseconds
/ 1000.0);
135 static constexpr BaseTimeDuration
Zero() { return BaseTimeDuration(); }
136 static constexpr BaseTimeDuration
Forever() { return FromTicks(INT64_MAX
); }
138 BaseTimeDuration
operator+(const BaseTimeDuration
& aOther
) const {
139 return FromTicks(ValueCalculator::Add(mValue
, aOther
.mValue
));
141 BaseTimeDuration
operator-(const BaseTimeDuration
& aOther
) const {
142 return FromTicks(ValueCalculator::Subtract(mValue
, aOther
.mValue
));
144 BaseTimeDuration
& operator+=(const BaseTimeDuration
& aOther
) {
145 mValue
= ValueCalculator::Add(mValue
, aOther
.mValue
);
148 BaseTimeDuration
& operator-=(const BaseTimeDuration
& aOther
) {
149 mValue
= ValueCalculator::Subtract(mValue
, aOther
.mValue
);
152 BaseTimeDuration
operator-() const {
153 // We don't just use FromTicks(ValueCalculator::Subtract(0, mValue))
154 // since that won't give the correct result for -TimeDuration::Forever().
156 if (mValue
== INT64_MAX
) {
158 } else if (mValue
== INT64_MIN
) {
164 return FromTicks(ticks
);
167 static BaseTimeDuration
Max(const BaseTimeDuration
& aA
,
168 const BaseTimeDuration
& aB
) {
169 return FromTicks(std::max(aA
.mValue
, aB
.mValue
));
171 static BaseTimeDuration
Min(const BaseTimeDuration
& aA
,
172 const BaseTimeDuration
& aB
) {
173 return FromTicks(std::min(aA
.mValue
, aB
.mValue
));
177 int64_t GetValue() const { return mValue
; }
181 // Block double multiplier (slower, imprecise if long duration) - Bug 853398.
182 // If required, use MultDouble explicitly and with care.
183 BaseTimeDuration
operator*(const double aMultiplier
) const = delete;
185 // Block double divisor (for the same reason, and because dividing by
186 // fractional values would otherwise invoke the int64_t variant, and rounding
187 // the passed argument can then cause divide-by-zero) - Bug 1147491.
188 BaseTimeDuration
operator/(const double aDivisor
) const = delete;
191 BaseTimeDuration
MultDouble(double aMultiplier
) const {
192 return FromTicks(ValueCalculator::Multiply(mValue
, aMultiplier
));
194 BaseTimeDuration
operator*(const int32_t aMultiplier
) const {
195 return FromTicks(ValueCalculator::Multiply(mValue
, aMultiplier
));
197 BaseTimeDuration
operator*(const uint32_t aMultiplier
) const {
198 return FromTicks(ValueCalculator::Multiply(mValue
, aMultiplier
));
200 BaseTimeDuration
operator*(const int64_t aMultiplier
) const {
201 return FromTicks(ValueCalculator::Multiply(mValue
, aMultiplier
));
203 BaseTimeDuration
operator*(const uint64_t aMultiplier
) const {
204 if (aMultiplier
> INT64_MAX
) {
207 return FromTicks(ValueCalculator::Multiply(mValue
, aMultiplier
));
209 BaseTimeDuration
operator/(const int64_t aDivisor
) const {
210 MOZ_ASSERT(aDivisor
!= 0, "Division by zero");
211 return FromTicks(ValueCalculator::Divide(mValue
, aDivisor
));
213 double operator/(const BaseTimeDuration
& aOther
) const {
214 MOZ_ASSERT(aOther
.mValue
!= 0, "Division by zero");
215 return ValueCalculator::DivideDouble(mValue
, aOther
.mValue
);
217 BaseTimeDuration
operator%(const BaseTimeDuration
& aOther
) const {
218 MOZ_ASSERT(aOther
.mValue
!= 0, "Division by zero");
219 return FromTicks(ValueCalculator::Modulo(mValue
, aOther
.mValue
));
222 template <typename E
>
223 bool operator<(const BaseTimeDuration
<E
>& aOther
) const {
224 return mValue
< aOther
.mValue
;
226 template <typename E
>
227 bool operator<=(const BaseTimeDuration
<E
>& aOther
) const {
228 return mValue
<= aOther
.mValue
;
230 template <typename E
>
231 bool operator>=(const BaseTimeDuration
<E
>& aOther
) const {
232 return mValue
>= aOther
.mValue
;
234 template <typename E
>
235 bool operator>(const BaseTimeDuration
<E
>& aOther
) const {
236 return mValue
> aOther
.mValue
;
238 template <typename E
>
239 bool operator==(const BaseTimeDuration
<E
>& aOther
) const {
240 return mValue
== aOther
.mValue
;
242 template <typename E
>
243 bool operator!=(const BaseTimeDuration
<E
>& aOther
) const {
244 return mValue
!= aOther
.mValue
;
246 bool IsZero() const { return mValue
== 0; }
247 explicit operator bool() const { return mValue
!= 0; }
249 friend std::ostream
& operator<<(std::ostream
& aStream
,
250 const BaseTimeDuration
& aDuration
) {
251 return aStream
<< aDuration
.ToMilliseconds() << " ms";
254 // Return a best guess at the system's current timing resolution,
255 // which might be variable. BaseTimeDurations below this order of
256 // magnitude are meaningless, and those at the same order of
257 // magnitude or just above are suspect.
258 static BaseTimeDuration
Resolution() {
259 return FromTicks(BaseTimeDurationPlatformUtils::ResolutionInTicks());
262 // We could define additional operators here:
263 // -- convert to/from other time units
264 // -- scale duration by a float
265 // but let's do that on demand.
266 // Comparing durations for equality will only lead to bugs on
267 // platforms with high-resolution timers.
270 friend class TimeStamp
;
271 friend struct IPC::ParamTraits
<mozilla::BaseTimeDuration
<ValueCalculator
>>;
273 friend class BaseTimeDuration
;
275 static constexpr BaseTimeDuration
FromTicks(int64_t aTicks
) {
281 static BaseTimeDuration
FromTicks(double aTicks
) {
282 // NOTE: this MUST be a >= test, because int64_t(double(INT64_MAX))
283 // overflows and gives INT64_MIN.
284 if (aTicks
>= double(INT64_MAX
)) {
285 return FromTicks(INT64_MAX
);
288 // This MUST be a <= test.
289 if (aTicks
<= double(INT64_MIN
)) {
290 return FromTicks(INT64_MIN
);
293 return FromTicks(int64_t(aTicks
));
296 // Duration, result is implementation-specific difference of two TimeStamps
301 * Perform arithmetic operations on the value of a BaseTimeDuration without
302 * doing strict checks on the range of values.
304 class TimeDurationValueCalculator
{
306 static int64_t Add(int64_t aA
, int64_t aB
) { return aA
+ aB
; }
307 static int64_t Subtract(int64_t aA
, int64_t aB
) { return aA
- aB
; }
309 template <typename T
>
310 static int64_t Multiply(int64_t aA
, T aB
) {
311 static_assert(std::is_integral_v
<T
>,
312 "Using integer multiplication routine with non-integer type."
313 " Further specialization required");
314 return aA
* static_cast<int64_t>(aB
);
317 static int64_t Divide(int64_t aA
, int64_t aB
) { return aA
/ aB
; }
318 static double DivideDouble(int64_t aA
, int64_t aB
) {
319 return static_cast<double>(aA
) / aB
;
321 static int64_t Modulo(int64_t aA
, int64_t aB
) { return aA
% aB
; }
325 inline int64_t TimeDurationValueCalculator::Multiply
<double>(int64_t aA
,
327 return static_cast<int64_t>(aA
* aB
);
331 * Specialization of BaseTimeDuration that uses TimeDurationValueCalculator for
332 * arithmetic on the mValue member.
334 * Use this class for time durations that are *not* expected to hold values of
335 * Forever (or the negative equivalent) or when such time duration are *not*
336 * expected to be used in arithmetic operations.
338 typedef BaseTimeDuration
<TimeDurationValueCalculator
> TimeDuration
;
341 * Instances of this class represent moments in time, or a special
342 * "null" moment. We do not use the non-monotonic system clock or
343 * local time, since they can be reset, causing apparent backward
344 * travel in time, which can confuse algorithms. Instead we measure
345 * elapsed time according to the system. This time can never go
346 * backwards (i.e. it never wraps around, at least not in less than
347 * five million years of system elapsed time). It might not advance
348 * while the system is sleeping. If TimeStamp::SetNow() is not called
349 * at all for hours or days, we might not notice the passage of some
352 * We deliberately do not expose a way to convert TimeStamps to some
353 * particular unit. All you can do is compute a difference between two
354 * TimeStamps to get a TimeDuration. You can also add a TimeDuration
355 * to a TimeStamp to get a new TimeStamp. You can't do something
356 * meaningless like add two TimeStamps.
358 * Internally this is implemented as either a wrapper around
359 * - high-resolution, monotonic, system clocks if they exist on this
361 * - PRIntervalTime otherwise. We detect wraparounds of
362 * PRIntervalTime and work around them.
364 * This class is similar to C++11's time_point, however it is
365 * explicitly nullable and provides an IsNull() method. time_point
366 * is initialized to the clock's epoch and provides a
367 * time_since_epoch() method that functions similiarly. i.e.
368 * t.IsNull() is equivalent to t.time_since_epoch() ==
369 * decltype(t)::duration::zero();
371 * Note that, since TimeStamp objects are small, prefer to pass them by value
372 * unless there is a specific reason not to do so.
375 // If this static_assert fails then possibly the warning comment below is no
376 // longer valid and should be removed.
377 static_assert(sizeof(TimeStampValue
) > 8);
380 * WARNING: On Windows, each TimeStamp is represented internally by two
381 * different raw values (one from GTC and one from QPC) and which value gets
382 * used for a given operation depends on whether both operands have QPC values
383 * or not. This duality of values can lead to some surprising results when
384 * mixing TimeStamps with and without QPC values, such as comparisons being
385 * non-transitive (ie, a > b > c might not imply a > c). See bug 1829983 for
386 * more details/an example.
391 * Initialize to the "null" moment
393 constexpr TimeStamp() : mValue(0) {}
394 // Default copy-constructor and assignment are OK
397 * The system timestamps are the same as the TimeStamp
398 * retrieved by mozilla::TimeStamp. Since we need this for
399 * vsync timestamps, we enable the creation of mozilla::TimeStamps
400 * on platforms that support vsync aligned refresh drivers / compositors
401 * Verified true as of Jan 31, 2015: B2G and OS X
403 * Android's event time uses CLOCK_MONOTONIC via SystemClock.uptimeMilles.
404 * So it is same value of TimeStamp posix implementation.
405 * Wayland/GTK event time also uses CLOCK_MONOTONIC on Weston/Mutter
407 * UNTESTED ON OTHER PLATFORMS
409 #if defined(XP_DARWIN) || defined(MOZ_WIDGET_ANDROID) || defined(MOZ_WIDGET_GTK)
410 static TimeStamp
FromSystemTime(int64_t aSystemTime
) {
411 static_assert(sizeof(aSystemTime
) == sizeof(TimeStampValue
),
412 "System timestamp should be same units as TimeStampValue");
413 return TimeStamp(aSystemTime
);
418 * Return true if this is the "null" moment
420 constexpr bool IsNull() const { return mValue
== 0; }
423 * Return true if this is not the "null" moment, may be used in tests, e.g.:
424 * |if (timestamp) { ... }|
426 explicit operator bool() const { return mValue
!= 0; }
429 * Return a timestamp reflecting the current elapsed system time. This
430 * is monotonically increasing (i.e., does not decrease) over the
431 * lifetime of this process' XPCOM session.
433 * Now() is trying to ensure the best possible precision on each platform,
434 * at least one millisecond.
436 * NowLoRes() has been introduced to workaround performance problems of
437 * QueryPerformanceCounter on the Windows platform. NowLoRes() is giving
438 * lower precision, usually 15.6 ms, but with very good performance benefit.
439 * Use it for measurements of longer times, like >200ms timeouts.
441 static TimeStamp
Now() { return Now(true); }
442 static TimeStamp
NowLoRes() { return Now(false); }
445 * Return a timestamp representing the time when the current process was
446 * created which will be comparable with other timestamps taken with this
449 * @returns A timestamp representing the time when the process was created
451 static MFBT_API TimeStamp
ProcessCreation();
454 * Return the very first timestamp that was taken. This can be used instead
455 * of TimeStamp::ProcessCreation() by code that might not allow running the
456 * complex logic required to compute the real process creation. This will
457 * necessarily have been recorded sometimes after TimeStamp::ProcessCreation()
458 * or at best should be equal to it.
460 * @returns The first tiemstamp that was taken by this process
462 static MFBT_API TimeStamp
FirstTimeStamp();
465 * Records a process restart. After this call ProcessCreation() will return
466 * the time when the browser was restarted instead of the actual time when
467 * the process was created.
469 static MFBT_API
void RecordProcessRestart();
472 uint64_t RawClockMonotonicNanosecondsSinceBoot() const {
473 return static_cast<uint64_t>(mValue
);
478 // Returns the number of nanoseconds since the mach_absolute_time origin.
479 MFBT_API
uint64_t RawMachAbsoluteTimeNanoseconds() const;
483 Maybe
<uint64_t> RawQueryPerformanceCounterValue() const {
484 // mQPC is stored in `mt` i.e. QueryPerformanceCounter * 1000
485 // so divide out the 1000
486 return mValue
.mHasQPC
? Some(mValue
.mQPC
/ 1000ULL) : Nothing();
491 * Compute the difference between two timestamps. Both must be non-null.
493 TimeDuration
operator-(const TimeStamp
& aOther
) const {
494 MOZ_ASSERT(!IsNull(), "Cannot compute with a null value");
495 MOZ_ASSERT(!aOther
.IsNull(), "Cannot compute with aOther null value");
496 static_assert(-INT64_MAX
> INT64_MIN
, "int64_t sanity check");
497 int64_t ticks
= int64_t(mValue
- aOther
.mValue
);
498 // Check for overflow.
499 if (mValue
> aOther
.mValue
) {
508 return TimeDuration::FromTicks(ticks
);
511 TimeStamp
operator+(const TimeDuration
& aOther
) const {
512 TimeStamp result
= *this;
516 TimeStamp
operator-(const TimeDuration
& aOther
) const {
517 TimeStamp result
= *this;
521 TimeStamp
& operator+=(const TimeDuration
& aOther
) {
522 MOZ_ASSERT(!IsNull(), "Cannot compute with a null value");
523 TimeStampValue value
= mValue
+ aOther
.mValue
;
524 // Check for underflow.
525 // (We don't check for overflow because it's not obvious what the error
526 // behavior should be in that case.)
527 if (aOther
.mValue
< 0 && value
> mValue
) {
533 TimeStamp
& operator-=(const TimeDuration
& aOther
) {
534 MOZ_ASSERT(!IsNull(), "Cannot compute with a null value");
535 TimeStampValue value
= mValue
- aOther
.mValue
;
536 // Check for underflow.
537 // (We don't check for overflow because it's not obvious what the error
538 // behavior should be in that case.)
539 if (aOther
.mValue
> 0 && value
> mValue
) {
546 constexpr bool operator<(const TimeStamp
& aOther
) const {
547 MOZ_ASSERT(!IsNull(), "Cannot compute with a null value");
548 MOZ_ASSERT(!aOther
.IsNull(), "Cannot compute with aOther null value");
549 return mValue
< aOther
.mValue
;
551 constexpr bool operator<=(const TimeStamp
& aOther
) const {
552 MOZ_ASSERT(!IsNull(), "Cannot compute with a null value");
553 MOZ_ASSERT(!aOther
.IsNull(), "Cannot compute with aOther null value");
554 return mValue
<= aOther
.mValue
;
556 constexpr bool operator>=(const TimeStamp
& aOther
) const {
557 MOZ_ASSERT(!IsNull(), "Cannot compute with a null value");
558 MOZ_ASSERT(!aOther
.IsNull(), "Cannot compute with aOther null value");
559 return mValue
>= aOther
.mValue
;
561 constexpr bool operator>(const TimeStamp
& aOther
) const {
562 MOZ_ASSERT(!IsNull(), "Cannot compute with a null value");
563 MOZ_ASSERT(!aOther
.IsNull(), "Cannot compute with aOther null value");
564 return mValue
> aOther
.mValue
;
566 bool operator==(const TimeStamp
& aOther
) const {
567 return IsNull() ? aOther
.IsNull()
568 : !aOther
.IsNull() && mValue
== aOther
.mValue
;
570 bool operator!=(const TimeStamp
& aOther
) const { return !(*this == aOther
); }
572 // Comparing TimeStamps for equality should be discouraged. Adding
573 // two TimeStamps, or scaling TimeStamps, is nonsense and must never
576 static MFBT_API
void Startup();
577 static MFBT_API
void Shutdown();
580 TimeStampValue
GetValue() const { return mValue
; }
584 friend struct IPC::ParamTraits
<mozilla::TimeStamp
>;
585 friend struct TimeStampInitialization
;
586 friend class TimeStampTests
;
588 constexpr MOZ_IMPLICIT
TimeStamp(TimeStampValue aValue
) : mValue(aValue
) {}
590 static MFBT_API TimeStamp
Now(bool aHighResolution
);
593 * Computes the uptime of the current process in microseconds. The result
594 * is platform-dependent and needs to be checked against existing timestamps
597 * @returns The number of microseconds since the calling process was started
598 * or 0 if an error was encountered while computing the uptime
600 static MFBT_API
uint64_t ComputeProcessUptime();
603 * When built with PRIntervalTime, a value of 0 means this instance
604 * is "null". Otherwise, the low 32 bits represent a PRIntervalTime,
605 * and the high 32 bits represent a counter of the number of
606 * rollovers of PRIntervalTime that we've seen. This counter starts
607 * at 1 to avoid a real time colliding with the "null" value.
609 * PR_INTERVAL_MAX is set at 100,000 ticks per second. So the minimum
610 * time to wrap around is about 2^64/100000 seconds, i.e. about
613 * When using a system clock, a value is system dependent.
615 TimeStampValue mValue
;
618 } // namespace mozilla
620 #endif /* mozilla_TimeStamp_h */