Bug 1773205 [wpt PR 34343] - SVG Text NG: Improve performance on ancestor scaling...
[gecko.git] / mozglue / misc / TimeStamp_posix.cpp
blob10c046d04699cad3f4ced55253d66dc693be74ed
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 //
8 // Implement TimeStamp::Now() with POSIX clocks.
9 //
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>
17 #include <time.h>
18 #include <unistd.h>
19 #include <string.h>
21 #if defined(__DragonFly__) || defined(__FreeBSD__) || defined(__NetBSD__) || \
22 defined(__OpenBSD__)
23 # include <sys/param.h>
24 # include <sys/sysctl.h>
25 #endif
27 #if defined(__DragonFly__) || defined(__FreeBSD__)
28 # include <sys/user.h>
29 #endif
31 #if defined(__NetBSD__)
32 # undef KERN_PROC
33 # define KERN_PROC KERN_PROC2
34 # define KINFO_PROC struct kinfo_proc2
35 #else
36 # define KINFO_PROC struct kinfo_proc
37 #endif
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
45 #else
46 # define KP_START_SEC p_ustart_sec
47 # define KP_START_USEC p_ustart_usec
48 #endif
50 #include "mozilla/Sprintf.h"
51 #include "mozilla/TimeStamp.h"
53 #if !defined(__wasi__)
54 # include <pthread.h>
55 #endif
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;
63 #endif
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() {
76 struct timespec ts;
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
86 // the year 2037.
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
96 // overhead.
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();
107 end = ClockTimeNs();
109 uint64_t candidate = (start - end);
110 if (candidate < minres) {
111 minres = candidate;
115 if (0 == minres) {
116 // measurable resolution is either incredibly low, ~1ns, or very
117 // high. fall back on clock_getres()
118 struct timespec ts;
119 if (0 == clock_getres(CLOCK_MONOTONIC, &ts)) {
120 minres = TimespecToNs(ts);
124 if (0 == minres) {
125 // clock_getres probably failed. fall back on NSPR's resolution
126 // assumption
127 minres = 1 * kNsPerMs;
130 return minres;
133 namespace mozilla {
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)) {
151 return INT64_MAX;
153 if (result < INT64_MIN) {
154 return INT64_MIN;
157 return result;
160 int64_t BaseTimeDurationPlatformUtils::ResolutionInTicks() {
161 return static_cast<int64_t>(sResolution);
164 static bool gInitialized = false;
166 void TimeStamp::Startup() {
167 if (gInitialized) {
168 return;
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)
185 gInitialized = true;
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) {
201 char stat[512];
203 FILE* f = fopen(aFile, "r");
204 if (!f) {
205 return 0;
208 int n = fread(&stat, 1, sizeof(stat) - 1, f);
210 fclose(f);
212 if (n <= 0) {
213 return 0;
216 stat[n] = 0;
218 long long unsigned startTime = 0; // instead of uint64_t to keep GCC quiet
219 char* s = strrchr(stat, ')');
221 if (!s) {
222 return 0;
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",
228 &startTime);
230 if (rv != 1 || !startTime) {
231 return 0;
234 return 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);
247 *uptime = 0;
249 if (!hz) {
250 return nullptr;
253 char threadStat[40];
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) {
261 return nullptr;
264 *uptime = ((threadJiffies - selfJiffies) * kNsPerSec) / hz;
265 return nullptr;
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() {
272 uint64_t uptime = 0;
273 pthread_t uptime_pthread;
275 if (pthread_create(&uptime_pthread, nullptr, ComputeProcessUptimeThread,
276 &uptime)) {
277 MOZ_CRASH("Failed to create process uptime thread.");
278 return 0;
281 pthread_join(uptime_pthread, NULL);
283 return uptime / kNsPerUs;
286 #elif defined(__DragonFly__) || defined(__FreeBSD__) || defined(__NetBSD__) || \
287 defined(__OpenBSD__)
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() {
293 struct timespec ts;
294 int rv = clock_gettime(CLOCK_REALTIME, &ts);
296 if (rv == -1) {
297 return 0;
300 int mib[] = {
301 CTL_KERN,
302 KERN_PROC,
303 KERN_PROC_PID,
304 getpid(),
305 # if defined(__NetBSD__) || defined(__OpenBSD__)
306 sizeof(KINFO_PROC),
308 # endif
310 u_int mibLen = sizeof(mib) / sizeof(mib[0]);
312 KINFO_PROC proc;
313 size_t bufferSize = sizeof(proc);
314 rv = sysctl(mib, mibLen, &proc, &bufferSize, nullptr, 0);
316 if (rv == -1) {
317 return 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) {
325 return 0;
328 return (now - startTime) / kNsPerUs;
331 #else
333 uint64_t TimeStamp::ComputeProcessUptime() { return 0; }
335 #endif
337 } // namespace mozilla