xref: /aosp_15_r20/external/cronet/third_party/google_benchmark/src/src/timers.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2015 Google Inc. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "timers.h"
16 
17 #include "internal_macros.h"
18 
19 #ifdef BENCHMARK_OS_WINDOWS
20 #include <shlwapi.h>
21 #undef StrCat  // Don't let StrCat in string_util.h be renamed to lstrcatA
22 #include <versionhelpers.h>
23 #include <windows.h>
24 #else
25 #include <fcntl.h>
26 #if !defined(BENCHMARK_OS_FUCHSIA) && !defined(BENCHMARK_OS_QURT)
27 #include <sys/resource.h>
28 #endif
29 #include <sys/time.h>
30 #include <sys/types.h>  // this header must be included before 'sys/sysctl.h' to avoid compilation error on FreeBSD
31 #include <unistd.h>
32 #if defined BENCHMARK_OS_FREEBSD || defined BENCHMARK_OS_DRAGONFLY || \
33     defined BENCHMARK_OS_MACOSX
34 #include <sys/sysctl.h>
35 #endif
36 #if defined(BENCHMARK_OS_MACOSX)
37 #include <mach/mach_init.h>
38 #include <mach/mach_port.h>
39 #include <mach/thread_act.h>
40 #endif
41 #if defined(BENCHMARK_OS_QURT)
42 #include <qurt.h>
43 #endif
44 #endif
45 
46 #ifdef BENCHMARK_OS_EMSCRIPTEN
47 #include <emscripten.h>
48 #endif
49 
50 #include <cerrno>
51 #include <cstdint>
52 #include <cstdio>
53 #include <cstdlib>
54 #include <cstring>
55 #include <ctime>
56 #include <iostream>
57 #include <limits>
58 #include <mutex>
59 
60 #include "check.h"
61 #include "log.h"
62 #include "string_util.h"
63 
64 namespace benchmark {
65 
66 // Suppress unused warnings on helper functions.
67 #if defined(__GNUC__)
68 #pragma GCC diagnostic ignored "-Wunused-function"
69 #endif
70 #if defined(__NVCOMPILER)
71 #pragma diag_suppress declared_but_not_referenced
72 #endif
73 
74 namespace {
75 #if defined(BENCHMARK_OS_WINDOWS)
MakeTime(FILETIME const & kernel_time,FILETIME const & user_time)76 double MakeTime(FILETIME const& kernel_time, FILETIME const& user_time) {
77   ULARGE_INTEGER kernel;
78   ULARGE_INTEGER user;
79   kernel.HighPart = kernel_time.dwHighDateTime;
80   kernel.LowPart = kernel_time.dwLowDateTime;
81   user.HighPart = user_time.dwHighDateTime;
82   user.LowPart = user_time.dwLowDateTime;
83   return (static_cast<double>(kernel.QuadPart) +
84           static_cast<double>(user.QuadPart)) *
85          1e-7;
86 }
87 #elif !defined(BENCHMARK_OS_FUCHSIA) && !defined(BENCHMARK_OS_QURT)
88 double MakeTime(struct rusage const& ru) {
89   return (static_cast<double>(ru.ru_utime.tv_sec) +
90           static_cast<double>(ru.ru_utime.tv_usec) * 1e-6 +
91           static_cast<double>(ru.ru_stime.tv_sec) +
92           static_cast<double>(ru.ru_stime.tv_usec) * 1e-6);
93 }
94 #endif
95 #if defined(BENCHMARK_OS_MACOSX)
MakeTime(thread_basic_info_data_t const & info)96 double MakeTime(thread_basic_info_data_t const& info) {
97   return (static_cast<double>(info.user_time.seconds) +
98           static_cast<double>(info.user_time.microseconds) * 1e-6 +
99           static_cast<double>(info.system_time.seconds) +
100           static_cast<double>(info.system_time.microseconds) * 1e-6);
101 }
102 #endif
103 #if defined(CLOCK_PROCESS_CPUTIME_ID) || defined(CLOCK_THREAD_CPUTIME_ID)
MakeTime(struct timespec const & ts)104 double MakeTime(struct timespec const& ts) {
105   return ts.tv_sec + (static_cast<double>(ts.tv_nsec) * 1e-9);
106 }
107 #endif
108 
DiagnoseAndExit(const char * msg)109 BENCHMARK_NORETURN static void DiagnoseAndExit(const char* msg) {
110   std::cerr << "ERROR: " << msg << std::endl;
111   std::exit(EXIT_FAILURE);
112 }
113 
114 }  // end namespace
115 
ProcessCPUUsage()116 double ProcessCPUUsage() {
117 #if defined(BENCHMARK_OS_WINDOWS)
118   HANDLE proc = GetCurrentProcess();
119   FILETIME creation_time;
120   FILETIME exit_time;
121   FILETIME kernel_time;
122   FILETIME user_time;
123   if (GetProcessTimes(proc, &creation_time, &exit_time, &kernel_time,
124                       &user_time))
125     return MakeTime(kernel_time, user_time);
126   DiagnoseAndExit("GetProccessTimes() failed");
127 #elif defined(BENCHMARK_OS_QURT)
128   return static_cast<double>(
129              qurt_timer_timetick_to_us(qurt_timer_get_ticks())) *
130          1.0e-6;
131 #elif defined(BENCHMARK_OS_EMSCRIPTEN)
132   // clock_gettime(CLOCK_PROCESS_CPUTIME_ID, ...) returns 0 on Emscripten.
133   // Use Emscripten-specific API. Reported CPU time would be exactly the
134   // same as total time, but this is ok because there aren't long-latency
135   // synchronous system calls in Emscripten.
136   return emscripten_get_now() * 1e-3;
137 #elif defined(CLOCK_PROCESS_CPUTIME_ID) && !defined(BENCHMARK_OS_MACOSX)
138   // FIXME We want to use clock_gettime, but its not available in MacOS 10.11.
139   // See https://github.com/google/benchmark/pull/292
140   struct timespec spec;
141   if (clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &spec) == 0)
142     return MakeTime(spec);
143   DiagnoseAndExit("clock_gettime(CLOCK_PROCESS_CPUTIME_ID, ...) failed");
144 #else
145   struct rusage ru;
146   if (getrusage(RUSAGE_SELF, &ru) == 0) return MakeTime(ru);
147   DiagnoseAndExit("getrusage(RUSAGE_SELF, ...) failed");
148 #endif
149 }
150 
ThreadCPUUsage()151 double ThreadCPUUsage() {
152 #if defined(BENCHMARK_OS_WINDOWS)
153   HANDLE this_thread = GetCurrentThread();
154   FILETIME creation_time;
155   FILETIME exit_time;
156   FILETIME kernel_time;
157   FILETIME user_time;
158   GetThreadTimes(this_thread, &creation_time, &exit_time, &kernel_time,
159                  &user_time);
160   return MakeTime(kernel_time, user_time);
161 #elif defined(BENCHMARK_OS_QURT)
162   return static_cast<double>(
163              qurt_timer_timetick_to_us(qurt_timer_get_ticks())) *
164          1.0e-6;
165 #elif defined(BENCHMARK_OS_MACOSX)
166   // FIXME We want to use clock_gettime, but its not available in MacOS 10.11.
167   // See https://github.com/google/benchmark/pull/292
168   mach_msg_type_number_t count = THREAD_BASIC_INFO_COUNT;
169   thread_basic_info_data_t info;
170   mach_port_t thread = pthread_mach_thread_np(pthread_self());
171   if (thread_info(thread, THREAD_BASIC_INFO,
172                   reinterpret_cast<thread_info_t>(&info),
173                   &count) == KERN_SUCCESS) {
174     return MakeTime(info);
175   }
176   DiagnoseAndExit("ThreadCPUUsage() failed when evaluating thread_info");
177 #elif defined(BENCHMARK_OS_EMSCRIPTEN)
178   // Emscripten doesn't support traditional threads
179   return ProcessCPUUsage();
180 #elif defined(BENCHMARK_OS_RTEMS)
181   // RTEMS doesn't support CLOCK_THREAD_CPUTIME_ID. See
182   // https://github.com/RTEMS/rtems/blob/master/cpukit/posix/src/clockgettime.c
183   return ProcessCPUUsage();
184 #elif defined(BENCHMARK_OS_SOLARIS)
185   struct rusage ru;
186   if (getrusage(RUSAGE_LWP, &ru) == 0) return MakeTime(ru);
187   DiagnoseAndExit("getrusage(RUSAGE_LWP, ...) failed");
188 #elif defined(CLOCK_THREAD_CPUTIME_ID)
189   struct timespec ts;
190   if (clock_gettime(CLOCK_THREAD_CPUTIME_ID, &ts) == 0) return MakeTime(ts);
191   DiagnoseAndExit("clock_gettime(CLOCK_THREAD_CPUTIME_ID, ...) failed");
192 #else
193 #error Per-thread timing is not available on your system.
194 #endif
195 }
196 
LocalDateTimeString()197 std::string LocalDateTimeString() {
198   // Write the local time in RFC3339 format yyyy-mm-ddTHH:MM:SS+/-HH:MM.
199   typedef std::chrono::system_clock Clock;
200   std::time_t now = Clock::to_time_t(Clock::now());
201   const std::size_t kTzOffsetLen = 6;
202   const std::size_t kTimestampLen = 19;
203 
204   std::size_t tz_len;
205   std::size_t timestamp_len;
206   long int offset_minutes;
207   char tz_offset_sign = '+';
208   // tz_offset is set in one of three ways:
209   // * strftime with %z - This either returns empty or the ISO 8601 time.  The
210   // maximum length an
211   //   ISO 8601 string can be is 7 (e.g. -03:30, plus trailing zero).
212   // * snprintf with %c%02li:%02li - The maximum length is 41 (one for %c, up to
213   // 19 for %02li,
214   //   one for :, up to 19 %02li, plus trailing zero).
215   // * A fixed string of "-00:00".  The maximum length is 7 (-00:00, plus
216   // trailing zero).
217   //
218   // Thus, the maximum size this needs to be is 41.
219   char tz_offset[41];
220   // Long enough buffer to avoid format-overflow warnings
221   char storage[128];
222 
223 #if defined(BENCHMARK_OS_WINDOWS)
224   std::tm* timeinfo_p = ::localtime(&now);
225 #else
226   std::tm timeinfo;
227   std::tm* timeinfo_p = &timeinfo;
228   ::localtime_r(&now, &timeinfo);
229 #endif
230 
231   tz_len = std::strftime(tz_offset, sizeof(tz_offset), "%z", timeinfo_p);
232 
233   if (tz_len < kTzOffsetLen && tz_len > 1) {
234     // Timezone offset was written. strftime writes offset as +HHMM or -HHMM,
235     // RFC3339 specifies an offset as +HH:MM or -HH:MM. To convert, we parse
236     // the offset as an integer, then reprint it to a string.
237 
238     offset_minutes = ::strtol(tz_offset, NULL, 10);
239     if (offset_minutes < 0) {
240       offset_minutes *= -1;
241       tz_offset_sign = '-';
242     }
243 
244     tz_len =
245         ::snprintf(tz_offset, sizeof(tz_offset), "%c%02li:%02li",
246                    tz_offset_sign, offset_minutes / 100, offset_minutes % 100);
247     BM_CHECK(tz_len == kTzOffsetLen);
248     ((void)tz_len);  // Prevent unused variable warning in optimized build.
249   } else {
250     // Unknown offset. RFC3339 specifies that unknown local offsets should be
251     // written as UTC time with -00:00 timezone.
252 #if defined(BENCHMARK_OS_WINDOWS)
253     // Potential race condition if another thread calls localtime or gmtime.
254     timeinfo_p = ::gmtime(&now);
255 #else
256     ::gmtime_r(&now, &timeinfo);
257 #endif
258 
259     strncpy(tz_offset, "-00:00", kTzOffsetLen + 1);
260   }
261 
262   timestamp_len =
263       std::strftime(storage, sizeof(storage), "%Y-%m-%dT%H:%M:%S", timeinfo_p);
264   BM_CHECK(timestamp_len == kTimestampLen);
265   // Prevent unused variable warning in optimized build.
266   ((void)kTimestampLen);
267 
268   std::strncat(storage, tz_offset, sizeof(storage) - timestamp_len - 1);
269   return std::string(storage);
270 }
271 
272 }  // end namespace benchmark
273