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 #include "AwakeTimeStamp.h"
13 #include "mozilla/Assertions.h"
14 #include "mozilla/DebugOnly.h"
18 static constexpr uint64_t kUSperS
= 1000000;
19 static constexpr uint64_t kUSperMS
= 1000;
21 static constexpr uint64_t kNSperUS
= 1000;
24 double AwakeTimeDuration::ToSeconds() const {
25 return static_cast<double>(mValueUs
) / kUSperS
;
27 double AwakeTimeDuration::ToMilliseconds() const {
28 return static_cast<double>(mValueUs
) / kUSperMS
;
30 double AwakeTimeDuration::ToMicroseconds() const {
31 return static_cast<double>(mValueUs
);
34 AwakeTimeDuration
AwakeTimeStamp::operator-(
35 AwakeTimeStamp
const& aOther
) const {
36 return AwakeTimeDuration(mValueUs
- aOther
.mValueUs
);
39 AwakeTimeStamp
AwakeTimeStamp::operator+(
40 const AwakeTimeDuration
& aDuration
) const {
41 return AwakeTimeStamp(mValueUs
+ aDuration
.mValueUs
);
44 void AwakeTimeStamp::operator+=(const AwakeTimeDuration
& aOther
) {
45 mValueUs
+= aOther
.mValueUs
;
48 void AwakeTimeStamp::operator-=(const AwakeTimeDuration
& aOther
) {
49 MOZ_ASSERT(mValueUs
>= aOther
.mValueUs
);
50 mValueUs
-= aOther
.mValueUs
;
54 #if defined(__APPLE__) && defined(__MACH__)
56 # include <sys/time.h>
57 # include <sys/types.h>
58 # include <mach/mach_time.h>
60 AwakeTimeStamp
AwakeTimeStamp::NowLoRes() {
61 return AwakeTimeStamp(clock_gettime_nsec_np(CLOCK_UPTIME_RAW
) / kNSperUS
);
66 // Number of hundreds of nanoseconds in a microsecond
67 static constexpr uint64_t kHNSperUS
= 10;
69 AwakeTimeStamp
AwakeTimeStamp::NowLoRes() {
70 ULONGLONG interrupt_time
;
71 DebugOnly
<bool> rv
= QueryUnbiasedInterruptTime(&interrupt_time
);
74 return AwakeTimeStamp(interrupt_time
/ kHNSperUS
);
77 #else // Linux and other POSIX but not macOS
80 uint64_t TimespecToMicroseconds(struct timespec aTs
) {
81 return aTs
.tv_sec
* kUSperS
+ aTs
.tv_nsec
/ kNSperUS
;
84 AwakeTimeStamp
AwakeTimeStamp::NowLoRes() {
85 struct timespec ts
= {0};
86 DebugOnly
<int> rv
= clock_gettime(CLOCK_MONOTONIC
, &ts
);
88 return AwakeTimeStamp(TimespecToMicroseconds(ts
));
93 }; // namespace mozilla