1 /*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #ifndef INCLUDE_PERFETTO_BASE_TIME_H_
18 #define INCLUDE_PERFETTO_BASE_TIME_H_
19
20 #include <time.h>
21
22 #include <chrono>
23 #include <string>
24
25 #include "perfetto/base/build_config.h"
26 #include "perfetto/base/logging.h"
27
28 #if PERFETTO_BUILDFLAG(PERFETTO_OS_APPLE)
29 #include <mach/mach_init.h>
30 #include <mach/mach_port.h>
31 #include <mach/mach_time.h>
32 #include <mach/thread_act.h>
33 #endif
34
35 #if PERFETTO_BUILDFLAG(PERFETTO_OS_WASM)
36 #include <emscripten/emscripten.h>
37 #endif
38
39 namespace perfetto {
40 namespace base {
41
42 using TimeSeconds = std::chrono::seconds;
43 using TimeMillis = std::chrono::milliseconds;
44 using TimeNanos = std::chrono::nanoseconds;
45
FromPosixTimespec(const struct timespec & ts)46 inline TimeNanos FromPosixTimespec(const struct timespec& ts) {
47 return TimeNanos(ts.tv_sec * 1000000000LL + ts.tv_nsec);
48 }
49
50 void SleepMicroseconds(unsigned interval_us);
51
52 #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
53
54 TimeNanos GetWallTimeNs();
55 TimeNanos GetThreadCPUTimeNs();
GetWallTimeRawNs()56 inline TimeNanos GetWallTimeRawNs() {
57 return GetWallTimeNs();
58 }
59
60 // TODO: Clock that counts time during suspend is not implemented on Windows.
GetBootTimeNs()61 inline TimeNanos GetBootTimeNs() {
62 return GetWallTimeNs();
63 }
64
65 #elif PERFETTO_BUILDFLAG(PERFETTO_OS_APPLE)
66
GetWallTimeNs()67 inline TimeNanos GetWallTimeNs() {
68 auto init_time_factor = []() -> uint64_t {
69 mach_timebase_info_data_t timebase_info;
70 mach_timebase_info(&timebase_info);
71 return timebase_info.numer / timebase_info.denom;
72 };
73
74 static uint64_t monotonic_timebase_factor = init_time_factor();
75 return TimeNanos(mach_absolute_time() * monotonic_timebase_factor);
76 }
77
GetWallTimeRawNs()78 inline TimeNanos GetWallTimeRawNs() {
79 return GetWallTimeNs();
80 }
81
82 // TODO: Clock that counts time during suspend is not implemented on Mac.
GetBootTimeNs()83 inline TimeNanos GetBootTimeNs() {
84 return GetWallTimeNs();
85 }
86
GetThreadCPUTimeNs()87 inline TimeNanos GetThreadCPUTimeNs() {
88 mach_port_t this_thread = mach_thread_self();
89 mach_msg_type_number_t count = THREAD_BASIC_INFO_COUNT;
90 thread_basic_info_data_t info{};
91 kern_return_t kr =
92 thread_info(this_thread, THREAD_BASIC_INFO,
93 reinterpret_cast<thread_info_t>(&info), &count);
94 mach_port_deallocate(mach_task_self(), this_thread);
95
96 if (kr != KERN_SUCCESS) {
97 PERFETTO_DFATAL("Failed to get CPU time.");
98 return TimeNanos(0);
99 }
100 return TimeNanos(info.user_time.seconds * 1000000000LL +
101 info.user_time.microseconds * 1000LL +
102 info.system_time.seconds * 1000000000LL +
103 info.system_time.microseconds * 1000LL);
104 }
105
106 #elif PERFETTO_BUILDFLAG(PERFETTO_OS_WASM)
107
GetWallTimeNs()108 inline TimeNanos GetWallTimeNs() {
109 return TimeNanos(static_cast<uint64_t>(emscripten_get_now()) * 1000000);
110 }
111
GetWallTimeRawNs()112 inline TimeNanos GetWallTimeRawNs() {
113 return GetWallTimeNs();
114 }
115
GetThreadCPUTimeNs()116 inline TimeNanos GetThreadCPUTimeNs() {
117 return TimeNanos(0);
118 }
119
120 // TODO: Clock that counts time during suspend is not implemented on WASM.
GetBootTimeNs()121 inline TimeNanos GetBootTimeNs() {
122 return GetWallTimeNs();
123 }
124
125 #elif PERFETTO_BUILDFLAG(PERFETTO_OS_NACL)
126
127 // Tracing time doesn't need to work on NaCl since its going away shortly. We
128 // just need to compile on it. The only function NaCl could support is
129 // GetWallTimeNs(), but to prevent false hope we leave it unimplemented.
130
GetWallTimeNs()131 inline TimeNanos GetWallTimeNs() {
132 return TimeNanos(0);
133 }
134
GetWallTimeRawNs()135 inline TimeNanos GetWallTimeRawNs() {
136 return TimeNanos(0);
137 }
138
GetThreadCPUTimeNs()139 inline TimeNanos GetThreadCPUTimeNs() {
140 return TimeNanos(0);
141 }
142
GetBootTimeNs()143 inline TimeNanos GetBootTimeNs() {
144 return TimeNanos(0);
145 }
146
147 #else // posix
148
149 constexpr clockid_t kWallTimeClockSource = CLOCK_MONOTONIC;
150
GetTimeInternalNs(clockid_t clk_id)151 inline TimeNanos GetTimeInternalNs(clockid_t clk_id) {
152 struct timespec ts = {};
153 PERFETTO_CHECK(clock_gettime(clk_id, &ts) == 0);
154 return FromPosixTimespec(ts);
155 }
156
157 // Return ns from boot. Conversely to GetWallTimeNs, this clock counts also time
158 // during suspend (when supported).
GetBootTimeNs()159 inline TimeNanos GetBootTimeNs() {
160 // Determine if CLOCK_BOOTTIME is available on the first call.
161 static const clockid_t kBootTimeClockSource = [] {
162 struct timespec ts = {};
163 int res = clock_gettime(CLOCK_BOOTTIME, &ts);
164 return res == 0 ? CLOCK_BOOTTIME : kWallTimeClockSource;
165 }();
166 return GetTimeInternalNs(kBootTimeClockSource);
167 }
168
GetWallTimeNs()169 inline TimeNanos GetWallTimeNs() {
170 return GetTimeInternalNs(kWallTimeClockSource);
171 }
172
GetWallTimeRawNs()173 inline TimeNanos GetWallTimeRawNs() {
174 return GetTimeInternalNs(CLOCK_MONOTONIC_RAW);
175 }
176
GetThreadCPUTimeNs()177 inline TimeNanos GetThreadCPUTimeNs() {
178 return GetTimeInternalNs(CLOCK_THREAD_CPUTIME_ID);
179 }
180 #endif
181
GetBootTimeS()182 inline TimeSeconds GetBootTimeS() {
183 return std::chrono::duration_cast<TimeSeconds>(GetBootTimeNs());
184 }
185
GetBootTimeMs()186 inline TimeMillis GetBootTimeMs() {
187 return std::chrono::duration_cast<TimeMillis>(GetBootTimeNs());
188 }
189
GetWallTimeMs()190 inline TimeMillis GetWallTimeMs() {
191 return std::chrono::duration_cast<TimeMillis>(GetWallTimeNs());
192 }
193
GetWallTimeS()194 inline TimeSeconds GetWallTimeS() {
195 return std::chrono::duration_cast<TimeSeconds>(GetWallTimeNs());
196 }
197
ToPosixTimespec(TimeMillis time)198 inline struct timespec ToPosixTimespec(TimeMillis time) {
199 struct timespec ts {};
200 const long time_s = static_cast<long>(time.count() / 1000);
201 ts.tv_sec = time_s;
202 ts.tv_nsec = (static_cast<long>(time.count()) - time_s * 1000L) * 1000000L;
203 return ts;
204 }
205
206 std::string GetTimeFmt(const std::string& fmt);
207
TimeGm(struct tm * tms)208 inline int64_t TimeGm(struct tm* tms) {
209 #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
210 return static_cast<int64_t>(_mkgmtime(tms));
211 #elif PERFETTO_BUILDFLAG(PERFETTO_OS_NACL)
212 // NaCL has no timegm.
213 if (tms) // Kinda if (true), but avoids "mark as noreturn" errors.
214 PERFETTO_FATAL("timegm not supported");
215 return -1;
216 #else
217 return static_cast<int64_t>(timegm(tms));
218 #endif
219 }
220
221 // Creates a time_t-compatible timestamp (seconds since epoch) from a tuple of
222 // y-m-d-h-m-s. It's a saner version of timegm(). Some remarks:
223 // The year is just the actual year (it's Y-1900 in timegm()).
224 // The month ranges 1-12 (it's 0-11 in timegm()).
MkTime(int year,int month,int day,int h,int m,int s)225 inline int64_t MkTime(int year, int month, int day, int h, int m, int s) {
226 PERFETTO_DCHECK(year >= 1900);
227 PERFETTO_DCHECK(month > 0 && month <= 12);
228 PERFETTO_DCHECK(day > 0 && day <= 31);
229 struct tm tms {};
230 tms.tm_year = year - 1900;
231 tms.tm_mon = month - 1;
232 tms.tm_mday = day;
233 tms.tm_hour = h;
234 tms.tm_min = m;
235 tms.tm_sec = s;
236 return TimeGm(&tms);
237 }
238
239 } // namespace base
240 } // namespace perfetto
241
242 #endif // INCLUDE_PERFETTO_BASE_TIME_H_
243