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 
24 #include "perfetto/base/build_config.h"
25 #include "perfetto/base/logging.h"
26 
27 #if PERFETTO_BUILDFLAG(PERFETTO_OS_MACOSX)
28 #include <mach/mach_init.h>
29 #include <mach/mach_port.h>
30 #include <mach/mach_time.h>
31 #include <mach/thread_act.h>
32 #endif
33 
34 #if PERFETTO_BUILDFLAG(PERFETTO_OS_WASM)
35 #include <emscripten/emscripten.h>
36 #endif
37 
38 namespace perfetto {
39 namespace base {
40 
41 using TimeSeconds = std::chrono::seconds;
42 using TimeMillis = std::chrono::milliseconds;
43 using TimeNanos = std::chrono::nanoseconds;
44 
FromPosixTimespec(const struct timespec & ts)45 inline TimeNanos FromPosixTimespec(const struct timespec& ts) {
46   return TimeNanos(ts.tv_sec * 1000000000LL + ts.tv_nsec);
47 }
48 
49 void SleepMicroseconds(unsigned interval_us);
50 
51 #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
52 
53 TimeNanos GetWallTimeNs();
54 TimeNanos GetThreadCPUTimeNs();
55 
56 // TODO: Clock that counts time during suspend is not implemented on Windows.
GetBootTimeNs()57 inline TimeNanos GetBootTimeNs() {
58   return GetWallTimeNs();
59 }
60 
61 #elif PERFETTO_BUILDFLAG(PERFETTO_OS_MACOSX)
62 
GetWallTimeNs()63 inline TimeNanos GetWallTimeNs() {
64   auto init_time_factor = []() -> uint64_t {
65     mach_timebase_info_data_t timebase_info;
66     mach_timebase_info(&timebase_info);
67     return timebase_info.numer / timebase_info.denom;
68   };
69 
70   static uint64_t monotonic_timebase_factor = init_time_factor();
71   return TimeNanos(mach_absolute_time() * monotonic_timebase_factor);
72 }
73 
74 // TODO: Clock that counts time during suspend is not implemented on Mac.
GetBootTimeNs()75 inline TimeNanos GetBootTimeNs() {
76   return GetWallTimeNs();
77 }
78 
GetThreadCPUTimeNs()79 inline TimeNanos GetThreadCPUTimeNs() {
80   mach_port_t this_thread = mach_thread_self();
81   mach_msg_type_number_t count = THREAD_BASIC_INFO_COUNT;
82   thread_basic_info_data_t info{};
83   kern_return_t kr =
84       thread_info(this_thread, THREAD_BASIC_INFO,
85                   reinterpret_cast<thread_info_t>(&info), &count);
86   mach_port_deallocate(mach_task_self(), this_thread);
87 
88   if (kr != KERN_SUCCESS) {
89     PERFETTO_DFATAL("Failed to get CPU time.");
90     return TimeNanos(0);
91   }
92   return TimeNanos(info.user_time.seconds * 1000000000LL +
93                    info.user_time.microseconds * 1000LL +
94                    info.system_time.seconds * 1000000000LL +
95                    info.system_time.microseconds * 1000LL);
96 }
97 
98 #elif PERFETTO_BUILDFLAG(PERFETTO_OS_WASM)
99 
GetWallTimeNs()100 inline TimeNanos GetWallTimeNs() {
101   return TimeNanos(static_cast<uint64_t>(emscripten_get_now()) * 1000000);
102 }
103 
GetThreadCPUTimeNs()104 inline TimeNanos GetThreadCPUTimeNs() {
105   return TimeNanos(0);
106 }
107 
108 // TODO: Clock that counts time during suspend is not implemented on WASM.
GetBootTimeNs()109 inline TimeNanos GetBootTimeNs() {
110   return GetWallTimeNs();
111 }
112 
113 #else
114 
115 constexpr clockid_t kWallTimeClockSource = CLOCK_MONOTONIC;
116 
GetTimeInternalNs(clockid_t clk_id)117 inline TimeNanos GetTimeInternalNs(clockid_t clk_id) {
118   struct timespec ts = {};
119   PERFETTO_CHECK(clock_gettime(clk_id, &ts) == 0);
120   return FromPosixTimespec(ts);
121 }
122 
123 // Return ns from boot. Conversely to GetWallTimeNs, this clock counts also time
124 // during suspend (when supported).
GetBootTimeNs()125 inline TimeNanos GetBootTimeNs() {
126   // Determine if CLOCK_BOOTTIME is available on the first call.
127   static const clockid_t kBootTimeClockSource = [] {
128     struct timespec ts = {};
129     int res = clock_gettime(CLOCK_BOOTTIME, &ts);
130     return res == 0 ? CLOCK_BOOTTIME : kWallTimeClockSource;
131   }();
132   return GetTimeInternalNs(kBootTimeClockSource);
133 }
134 
GetWallTimeNs()135 inline TimeNanos GetWallTimeNs() {
136   return GetTimeInternalNs(kWallTimeClockSource);
137 }
138 
GetThreadCPUTimeNs()139 inline TimeNanos GetThreadCPUTimeNs() {
140   return GetTimeInternalNs(CLOCK_THREAD_CPUTIME_ID);
141 }
142 
143 #endif
144 
GetWallTimeMs()145 inline TimeMillis GetWallTimeMs() {
146   return std::chrono::duration_cast<TimeMillis>(GetWallTimeNs());
147 }
148 
GetWallTimeS()149 inline TimeSeconds GetWallTimeS() {
150   return std::chrono::duration_cast<TimeSeconds>(GetWallTimeNs());
151 }
152 
ToPosixTimespec(TimeMillis time)153 inline struct timespec ToPosixTimespec(TimeMillis time) {
154   struct timespec ts {};
155   const long time_s = static_cast<long>(time.count() / 1000);
156   ts.tv_sec = time_s;
157   ts.tv_nsec = (static_cast<long>(time.count()) - time_s * 1000L) * 1000000L;
158   return ts;
159 }
160 
161 }  // namespace base
162 }  // namespace perfetto
163 
164 #endif  // INCLUDE_PERFETTO_BASE_TIME_H_
165