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/. */
8 // Implement TimeStamp::Now() with POSIX clocks.
10 // The "tick" unit for POSIX clocks is simply a nanosecond, as this is
11 // the smallest unit of time representable by struct timespec. That
12 // doesn't mean that a nanosecond is the resolution of TimeDurations
13 // obtained with this API; see TimeDuration::Resolution;
16 #include <sys/syscall.h>
21 #if defined(__DragonFly__) || defined(__FreeBSD__) || defined(__NetBSD__) || \
23 # include <sys/param.h>
24 # include <sys/sysctl.h>
27 #if defined(__DragonFly__) || defined(__FreeBSD__)
28 # include <sys/user.h>
31 #if defined(__NetBSD__)
33 # define KERN_PROC KERN_PROC2
34 # define KINFO_PROC struct kinfo_proc2
36 # define KINFO_PROC struct kinfo_proc
39 #if defined(__DragonFly__)
40 # define KP_START_SEC kp_start.tv_sec
41 # define KP_START_USEC kp_start.tv_usec
42 #elif defined(__FreeBSD__)
43 # define KP_START_SEC ki_start.tv_sec
44 # define KP_START_USEC ki_start.tv_usec
46 # define KP_START_SEC p_ustart_sec
47 # define KP_START_USEC p_ustart_usec
50 #include "mozilla/Sprintf.h"
51 #include "mozilla/TimeStamp.h"
53 #if !defined(__wasi__)
57 // Estimate of the smallest duration of time we can measure.
58 static uint64_t sResolution
;
59 static uint64_t sResolutionSigDigs
;
61 #if !defined(__wasi__)
62 static const uint16_t kNsPerUs
= 1000;
65 static const uint64_t kNsPerMs
= 1000000;
66 static const uint64_t kNsPerSec
= 1000000000;
67 static const double kNsPerMsd
= 1000000.0;
68 static const double kNsPerSecd
= 1000000000.0;
70 static uint64_t TimespecToNs(const struct timespec
& aTs
) {
71 uint64_t baseNs
= uint64_t(aTs
.tv_sec
) * kNsPerSec
;
72 return baseNs
+ uint64_t(aTs
.tv_nsec
);
75 static uint64_t ClockTimeNs() {
77 // this can't fail: we know &ts is valid, and TimeStamp::Startup()
78 // checks that CLOCK_MONOTONIC is supported (and aborts if not)
79 clock_gettime(CLOCK_MONOTONIC
, &ts
);
81 // tv_sec is defined to be relative to an arbitrary point in time,
82 // but it would be madness for that point in time to be earlier than
83 // the Epoch. So we can safely assume that even if time_t is 32
84 // bits, tv_sec won't overflow while the browser is open. Revisit
85 // this argument if we're still building with 32-bit time_t around
87 return TimespecToNs(ts
);
90 static uint64_t ClockResolutionNs() {
91 // NB: why not rely on clock_getres()? Two reasons: (i) it might
92 // lie, and (ii) it might return an "ideal" resolution that while
93 // theoretically true, could never be measured in practice. Since
94 // clock_gettime() likely involves a system call on your platform,
95 // the "actual" timing resolution shouldn't be lower than syscall
98 uint64_t start
= ClockTimeNs();
99 uint64_t end
= ClockTimeNs();
100 uint64_t minres
= (end
- start
);
102 // 10 total trials is arbitrary: what we're trying to avoid by
103 // looping is getting unlucky and being interrupted by a context
104 // switch or signal, or being bitten by paging/cache effects
105 for (int i
= 0; i
< 9; ++i
) {
106 start
= ClockTimeNs();
109 uint64_t candidate
= (start
- end
);
110 if (candidate
< minres
) {
116 // measurable resolution is either incredibly low, ~1ns, or very
117 // high. fall back on clock_getres()
119 if (0 == clock_getres(CLOCK_MONOTONIC
, &ts
)) {
120 minres
= TimespecToNs(ts
);
125 // clock_getres probably failed. fall back on NSPR's resolution
127 minres
= 1 * kNsPerMs
;
135 double BaseTimeDurationPlatformUtils::ToSeconds(int64_t aTicks
) {
136 return double(aTicks
) / kNsPerSecd
;
139 double BaseTimeDurationPlatformUtils::ToSecondsSigDigits(int64_t aTicks
) {
140 // don't report a value < mResolution ...
141 int64_t valueSigDigs
= sResolution
* (aTicks
/ sResolution
);
142 // and chop off insignificant digits
143 valueSigDigs
= sResolutionSigDigs
* (valueSigDigs
/ sResolutionSigDigs
);
144 return double(valueSigDigs
) / kNsPerSecd
;
147 int64_t BaseTimeDurationPlatformUtils::TicksFromMilliseconds(
148 double aMilliseconds
) {
149 double result
= aMilliseconds
* kNsPerMsd
;
150 if (result
> double(INT64_MAX
)) {
153 if (result
< INT64_MIN
) {
160 int64_t BaseTimeDurationPlatformUtils::ResolutionInTicks() {
161 return static_cast<int64_t>(sResolution
);
164 static bool gInitialized
= false;
166 void TimeStamp::Startup() {
171 struct timespec dummy
;
172 if (clock_gettime(CLOCK_MONOTONIC
, &dummy
) != 0) {
173 MOZ_CRASH("CLOCK_MONOTONIC is absent!");
176 sResolution
= ClockResolutionNs();
178 // find the number of significant digits in sResolution, for the
179 // sake of ToSecondsSigDigits()
180 for (sResolutionSigDigs
= 1; !(sResolutionSigDigs
== sResolution
||
181 10 * sResolutionSigDigs
> sResolution
);
182 sResolutionSigDigs
*= 10)
188 void TimeStamp::Shutdown() {}
190 TimeStamp
TimeStamp::Now(bool aHighResolution
) {
191 return TimeStamp(ClockTimeNs());
194 #if defined(XP_LINUX) || defined(ANDROID)
196 // Calculates the amount of jiffies that have elapsed since boot and up to the
197 // starttime value of a specific process as found in its /proc/*/stat file.
198 // Returns 0 if an error occurred.
200 static uint64_t JiffiesSinceBoot(const char* aFile
) {
203 FILE* f
= fopen(aFile
, "r");
208 int n
= fread(&stat
, 1, sizeof(stat
) - 1, f
);
218 long long unsigned startTime
= 0; // instead of uint64_t to keep GCC quiet
219 char* s
= strrchr(stat
, ')');
225 int rv
= sscanf(s
+ 2,
226 "%*c %*d %*d %*d %*d %*d %*u %*u %*u %*u "
227 "%*u %*u %*u %*d %*d %*d %*d %*d %*d %llu",
230 if (rv
!= 1 || !startTime
) {
237 // Computes the interval that has elapsed between the thread creation and the
238 // process creation by comparing the starttime fields in the respective
239 // /proc/*/stat files. The resulting value will be a good approximation of the
240 // process uptime. This value will be stored at the address pointed by aTime;
241 // if an error occurred 0 will be stored instead.
243 static void* ComputeProcessUptimeThread(void* aTime
) {
244 uint64_t* uptime
= static_cast<uint64_t*>(aTime
);
245 long hz
= sysconf(_SC_CLK_TCK
);
254 SprintfLiteral(threadStat
, "/proc/self/task/%d/stat",
255 (pid_t
)syscall(__NR_gettid
));
257 uint64_t threadJiffies
= JiffiesSinceBoot(threadStat
);
258 uint64_t selfJiffies
= JiffiesSinceBoot("/proc/self/stat");
260 if (!threadJiffies
|| !selfJiffies
) {
264 *uptime
= ((threadJiffies
- selfJiffies
) * kNsPerSec
) / hz
;
268 // Computes and returns the process uptime in us on Linux & its derivatives.
269 // Returns 0 if an error was encountered.
271 uint64_t TimeStamp::ComputeProcessUptime() {
273 pthread_t uptime_pthread
;
275 if (pthread_create(&uptime_pthread
, nullptr, ComputeProcessUptimeThread
,
277 MOZ_CRASH("Failed to create process uptime thread.");
281 pthread_join(uptime_pthread
, NULL
);
283 return uptime
/ kNsPerUs
;
286 #elif defined(__DragonFly__) || defined(__FreeBSD__) || defined(__NetBSD__) || \
289 // Computes and returns the process uptime in us on various BSD flavors.
290 // Returns 0 if an error was encountered.
292 uint64_t TimeStamp::ComputeProcessUptime() {
294 int rv
= clock_gettime(CLOCK_REALTIME
, &ts
);
305 # if defined(__NetBSD__) || defined(__OpenBSD__)
310 u_int mibLen
= sizeof(mib
) / sizeof(mib
[0]);
313 size_t bufferSize
= sizeof(proc
);
314 rv
= sysctl(mib
, mibLen
, &proc
, &bufferSize
, nullptr, 0);
320 uint64_t startTime
= ((uint64_t)proc
.KP_START_SEC
* kNsPerSec
) +
321 (proc
.KP_START_USEC
* kNsPerUs
);
322 uint64_t now
= ((uint64_t)ts
.tv_sec
* kNsPerSec
) + ts
.tv_nsec
;
324 if (startTime
> now
) {
328 return (now
- startTime
) / kNsPerUs
;
333 uint64_t TimeStamp::ComputeProcessUptime() { return 0; }
337 } // namespace mozilla