Bug 1852545 [wpt PR 41834] - [FedCM] Update wpt tests for AccountAutoSelectedFlag...
[gecko.git] / mozglue / misc / AwakeTimeStamp.cpp
bloba5c8ed4abd6a64853969271bac2b92f0741df70e
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"
9 #ifdef XP_WIN
10 # include <windows.h>
11 #endif
13 #include "mozilla/Assertions.h"
14 #include "mozilla/DebugOnly.h"
16 namespace mozilla {
18 static constexpr uint64_t kUSperS = 1000000;
19 static constexpr uint64_t kUSperMS = 1000;
20 #ifndef XP_WIN
21 static constexpr uint64_t kNSperUS = 1000;
22 #endif
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;
53 // Apple things
54 #if defined(__APPLE__) && defined(__MACH__)
55 # include <time.h>
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);
64 #elif defined(XP_WIN)
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);
72 MOZ_ASSERT(rv);
74 return AwakeTimeStamp(interrupt_time / kHNSperUS);
77 #else // Linux and other POSIX but not macOS
78 # include <time.h>
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);
87 MOZ_ASSERT(!rv);
88 return AwakeTimeStamp(TimespecToMicroseconds(ts));
91 #endif
93 }; // namespace mozilla