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 static_cast<double>(ts.tv_sec) +
106 (static_cast<double>(ts.tv_nsec) * 1e-9);
107 }
108 #endif
109
DiagnoseAndExit(const char * msg)110 BENCHMARK_NORETURN static void DiagnoseAndExit(const char* msg) {
111 std::cerr << "ERROR: " << msg << std::endl;
112 std::exit(EXIT_FAILURE);
113 }
114
115 } // end namespace
116
ProcessCPUUsage()117 double ProcessCPUUsage() {
118 #if defined(BENCHMARK_OS_WINDOWS)
119 HANDLE proc = GetCurrentProcess();
120 FILETIME creation_time;
121 FILETIME exit_time;
122 FILETIME kernel_time;
123 FILETIME user_time;
124 if (GetProcessTimes(proc, &creation_time, &exit_time, &kernel_time,
125 &user_time))
126 return MakeTime(kernel_time, user_time);
127 DiagnoseAndExit("GetProccessTimes() failed");
128 #elif defined(BENCHMARK_OS_QURT)
129 // Note that qurt_timer_get_ticks() is no longer documented as of SDK 5.3.0,
130 // and doesn't appear to work on at least some devices (eg Samsung S22),
131 // so let's use the actually-documented and apparently-equivalent
132 // qurt_sysclock_get_hw_ticks() call instead.
133 return static_cast<double>(
134 qurt_timer_timetick_to_us(qurt_sysclock_get_hw_ticks())) *
135 1.0e-6;
136 #elif defined(BENCHMARK_OS_EMSCRIPTEN)
137 // clock_gettime(CLOCK_PROCESS_CPUTIME_ID, ...) returns 0 on Emscripten.
138 // Use Emscripten-specific API. Reported CPU time would be exactly the
139 // same as total time, but this is ok because there aren't long-latency
140 // synchronous system calls in Emscripten.
141 return emscripten_get_now() * 1e-3;
142 #elif defined(CLOCK_PROCESS_CPUTIME_ID) && !defined(BENCHMARK_OS_MACOSX)
143 // FIXME We want to use clock_gettime, but its not available in MacOS 10.11.
144 // See https://github.com/google/benchmark/pull/292
145 struct timespec spec;
146 if (clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &spec) == 0)
147 return MakeTime(spec);
148 DiagnoseAndExit("clock_gettime(CLOCK_PROCESS_CPUTIME_ID, ...) failed");
149 #else
150 struct rusage ru;
151 if (getrusage(RUSAGE_SELF, &ru) == 0) return MakeTime(ru);
152 DiagnoseAndExit("getrusage(RUSAGE_SELF, ...) failed");
153 #endif
154 }
155
ThreadCPUUsage()156 double ThreadCPUUsage() {
157 #if defined(BENCHMARK_OS_WINDOWS)
158 HANDLE this_thread = GetCurrentThread();
159 FILETIME creation_time;
160 FILETIME exit_time;
161 FILETIME kernel_time;
162 FILETIME user_time;
163 GetThreadTimes(this_thread, &creation_time, &exit_time, &kernel_time,
164 &user_time);
165 return MakeTime(kernel_time, user_time);
166 #elif defined(BENCHMARK_OS_QURT)
167 // Note that qurt_timer_get_ticks() is no longer documented as of SDK 5.3.0,
168 // and doesn't appear to work on at least some devices (eg Samsung S22),
169 // so let's use the actually-documented and apparently-equivalent
170 // qurt_sysclock_get_hw_ticks() call instead.
171 return static_cast<double>(
172 qurt_timer_timetick_to_us(qurt_sysclock_get_hw_ticks())) *
173 1.0e-6;
174 #elif defined(BENCHMARK_OS_MACOSX)
175 // FIXME We want to use clock_gettime, but its not available in MacOS 10.11.
176 // See https://github.com/google/benchmark/pull/292
177 mach_msg_type_number_t count = THREAD_BASIC_INFO_COUNT;
178 thread_basic_info_data_t info;
179 mach_port_t thread = pthread_mach_thread_np(pthread_self());
180 if (thread_info(thread, THREAD_BASIC_INFO,
181 reinterpret_cast<thread_info_t>(&info),
182 &count) == KERN_SUCCESS) {
183 return MakeTime(info);
184 }
185 DiagnoseAndExit("ThreadCPUUsage() failed when evaluating thread_info");
186 #elif defined(BENCHMARK_OS_EMSCRIPTEN)
187 // Emscripten doesn't support traditional threads
188 return ProcessCPUUsage();
189 #elif defined(BENCHMARK_OS_RTEMS)
190 // RTEMS doesn't support CLOCK_THREAD_CPUTIME_ID. See
191 // https://github.com/RTEMS/rtems/blob/master/cpukit/posix/src/clockgettime.c
192 return ProcessCPUUsage();
193 #elif defined(BENCHMARK_OS_ZOS)
194 // z/OS doesn't support CLOCK_THREAD_CPUTIME_ID.
195 return ProcessCPUUsage();
196 #elif defined(BENCHMARK_OS_SOLARIS)
197 struct rusage ru;
198 if (getrusage(RUSAGE_LWP, &ru) == 0) return MakeTime(ru);
199 DiagnoseAndExit("getrusage(RUSAGE_LWP, ...) failed");
200 #elif defined(CLOCK_THREAD_CPUTIME_ID)
201 struct timespec ts;
202 if (clock_gettime(CLOCK_THREAD_CPUTIME_ID, &ts) == 0) return MakeTime(ts);
203 DiagnoseAndExit("clock_gettime(CLOCK_THREAD_CPUTIME_ID, ...) failed");
204 #else
205 #error Per-thread timing is not available on your system.
206 #endif
207 }
208
LocalDateTimeString()209 std::string LocalDateTimeString() {
210 // Write the local time in RFC3339 format yyyy-mm-ddTHH:MM:SS+/-HH:MM.
211 typedef std::chrono::system_clock Clock;
212 std::time_t now = Clock::to_time_t(Clock::now());
213 const std::size_t kTzOffsetLen = 6;
214 const std::size_t kTimestampLen = 19;
215
216 std::size_t tz_len;
217 std::size_t timestamp_len;
218 long int offset_minutes;
219 char tz_offset_sign = '+';
220 // tz_offset is set in one of three ways:
221 // * strftime with %z - This either returns empty or the ISO 8601 time. The
222 // maximum length an
223 // ISO 8601 string can be is 7 (e.g. -03:30, plus trailing zero).
224 // * snprintf with %c%02li:%02li - The maximum length is 41 (one for %c, up to
225 // 19 for %02li,
226 // one for :, up to 19 %02li, plus trailing zero).
227 // * A fixed string of "-00:00". The maximum length is 7 (-00:00, plus
228 // trailing zero).
229 //
230 // Thus, the maximum size this needs to be is 41.
231 char tz_offset[41];
232 // Long enough buffer to avoid format-overflow warnings
233 char storage[128];
234
235 #if defined(BENCHMARK_OS_WINDOWS)
236 std::tm* timeinfo_p = ::localtime(&now);
237 #else
238 std::tm timeinfo;
239 std::tm* timeinfo_p = &timeinfo;
240 ::localtime_r(&now, &timeinfo);
241 #endif
242
243 tz_len = std::strftime(tz_offset, sizeof(tz_offset), "%z", timeinfo_p);
244
245 if (tz_len < kTzOffsetLen && tz_len > 1) {
246 // Timezone offset was written. strftime writes offset as +HHMM or -HHMM,
247 // RFC3339 specifies an offset as +HH:MM or -HH:MM. To convert, we parse
248 // the offset as an integer, then reprint it to a string.
249
250 offset_minutes = ::strtol(tz_offset, NULL, 10);
251 if (offset_minutes < 0) {
252 offset_minutes *= -1;
253 tz_offset_sign = '-';
254 }
255
256 tz_len = static_cast<size_t>(
257 ::snprintf(tz_offset, sizeof(tz_offset), "%c%02li:%02li",
258 tz_offset_sign, offset_minutes / 100, offset_minutes % 100));
259 BM_CHECK(tz_len == kTzOffsetLen);
260 ((void)tz_len); // Prevent unused variable warning in optimized build.
261 } else {
262 // Unknown offset. RFC3339 specifies that unknown local offsets should be
263 // written as UTC time with -00:00 timezone.
264 #if defined(BENCHMARK_OS_WINDOWS)
265 // Potential race condition if another thread calls localtime or gmtime.
266 timeinfo_p = ::gmtime(&now);
267 #else
268 ::gmtime_r(&now, &timeinfo);
269 #endif
270
271 strncpy(tz_offset, "-00:00", kTzOffsetLen + 1);
272 }
273
274 timestamp_len =
275 std::strftime(storage, sizeof(storage), "%Y-%m-%dT%H:%M:%S", timeinfo_p);
276 BM_CHECK(timestamp_len == kTimestampLen);
277 // Prevent unused variable warning in optimized build.
278 ((void)kTimestampLen);
279
280 std::strncat(storage, tz_offset, sizeof(storage) - timestamp_len - 1);
281 return std::string(storage);
282 }
283
284 } // end namespace benchmark
285