[docs] Add LICENSE.txt to the root of the mono-repo
[llvm-project.git] / third-party / benchmark / src / timers.cc
blob21d3db20da9ed3440d9597803352319804915129
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.
15 #include "timers.h"
17 #include "internal_macros.h"
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 #ifndef BENCHMARK_OS_FUCHSIA
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 #endif
43 #ifdef BENCHMARK_OS_EMSCRIPTEN
44 #include <emscripten.h>
45 #endif
47 #include <cerrno>
48 #include <cstdint>
49 #include <cstdio>
50 #include <cstdlib>
51 #include <cstring>
52 #include <ctime>
53 #include <iostream>
54 #include <limits>
55 #include <mutex>
57 #include "check.h"
58 #include "log.h"
59 #include "sleep.h"
60 #include "string_util.h"
62 namespace benchmark {
64 // Suppress unused warnings on helper functions.
65 #if defined(__GNUC__)
66 #pragma GCC diagnostic ignored "-Wunused-function"
67 #endif
69 namespace {
70 #if defined(BENCHMARK_OS_WINDOWS)
71 double MakeTime(FILETIME const& kernel_time, FILETIME const& user_time) {
72 ULARGE_INTEGER kernel;
73 ULARGE_INTEGER user;
74 kernel.HighPart = kernel_time.dwHighDateTime;
75 kernel.LowPart = kernel_time.dwLowDateTime;
76 user.HighPart = user_time.dwHighDateTime;
77 user.LowPart = user_time.dwLowDateTime;
78 return (static_cast<double>(kernel.QuadPart) +
79 static_cast<double>(user.QuadPart)) *
80 1e-7;
82 #elif !defined(BENCHMARK_OS_FUCHSIA)
83 double MakeTime(struct rusage const& ru) {
84 return (static_cast<double>(ru.ru_utime.tv_sec) +
85 static_cast<double>(ru.ru_utime.tv_usec) * 1e-6 +
86 static_cast<double>(ru.ru_stime.tv_sec) +
87 static_cast<double>(ru.ru_stime.tv_usec) * 1e-6);
89 #endif
90 #if defined(BENCHMARK_OS_MACOSX)
91 double MakeTime(thread_basic_info_data_t const& info) {
92 return (static_cast<double>(info.user_time.seconds) +
93 static_cast<double>(info.user_time.microseconds) * 1e-6 +
94 static_cast<double>(info.system_time.seconds) +
95 static_cast<double>(info.system_time.microseconds) * 1e-6);
97 #endif
98 #if defined(CLOCK_PROCESS_CPUTIME_ID) || defined(CLOCK_THREAD_CPUTIME_ID)
99 double MakeTime(struct timespec const& ts) {
100 return ts.tv_sec + (static_cast<double>(ts.tv_nsec) * 1e-9);
102 #endif
104 BENCHMARK_NORETURN static void DiagnoseAndExit(const char* msg) {
105 std::cerr << "ERROR: " << msg << std::endl;
106 std::exit(EXIT_FAILURE);
109 } // end namespace
111 double ProcessCPUUsage() {
112 #if defined(BENCHMARK_OS_WINDOWS)
113 HANDLE proc = GetCurrentProcess();
114 FILETIME creation_time;
115 FILETIME exit_time;
116 FILETIME kernel_time;
117 FILETIME user_time;
118 if (GetProcessTimes(proc, &creation_time, &exit_time, &kernel_time,
119 &user_time))
120 return MakeTime(kernel_time, user_time);
121 DiagnoseAndExit("GetProccessTimes() failed");
122 #elif defined(BENCHMARK_OS_EMSCRIPTEN)
123 // clock_gettime(CLOCK_PROCESS_CPUTIME_ID, ...) returns 0 on Emscripten.
124 // Use Emscripten-specific API. Reported CPU time would be exactly the
125 // same as total time, but this is ok because there aren't long-latency
126 // syncronous system calls in Emscripten.
127 return emscripten_get_now() * 1e-3;
128 #elif defined(CLOCK_PROCESS_CPUTIME_ID) && !defined(BENCHMARK_OS_MACOSX)
129 // FIXME We want to use clock_gettime, but its not available in MacOS 10.11.
130 // See https://github.com/google/benchmark/pull/292
131 struct timespec spec;
132 if (clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &spec) == 0)
133 return MakeTime(spec);
134 DiagnoseAndExit("clock_gettime(CLOCK_PROCESS_CPUTIME_ID, ...) failed");
135 #else
136 struct rusage ru;
137 if (getrusage(RUSAGE_SELF, &ru) == 0) return MakeTime(ru);
138 DiagnoseAndExit("getrusage(RUSAGE_SELF, ...) failed");
139 #endif
142 double ThreadCPUUsage() {
143 #if defined(BENCHMARK_OS_WINDOWS)
144 HANDLE this_thread = GetCurrentThread();
145 FILETIME creation_time;
146 FILETIME exit_time;
147 FILETIME kernel_time;
148 FILETIME user_time;
149 GetThreadTimes(this_thread, &creation_time, &exit_time, &kernel_time,
150 &user_time);
151 return MakeTime(kernel_time, user_time);
152 #elif defined(BENCHMARK_OS_MACOSX)
153 // FIXME We want to use clock_gettime, but its not available in MacOS 10.11.
154 // See https://github.com/google/benchmark/pull/292
155 mach_msg_type_number_t count = THREAD_BASIC_INFO_COUNT;
156 thread_basic_info_data_t info;
157 mach_port_t thread = pthread_mach_thread_np(pthread_self());
158 if (thread_info(thread, THREAD_BASIC_INFO,
159 reinterpret_cast<thread_info_t>(&info),
160 &count) == KERN_SUCCESS) {
161 return MakeTime(info);
163 DiagnoseAndExit("ThreadCPUUsage() failed when evaluating thread_info");
164 #elif defined(BENCHMARK_OS_EMSCRIPTEN)
165 // Emscripten doesn't support traditional threads
166 return ProcessCPUUsage();
167 #elif defined(BENCHMARK_OS_RTEMS)
168 // RTEMS doesn't support CLOCK_THREAD_CPUTIME_ID. See
169 // https://github.com/RTEMS/rtems/blob/master/cpukit/posix/src/clockgettime.c
170 return ProcessCPUUsage();
171 #elif defined(BENCHMARK_OS_SOLARIS)
172 struct rusage ru;
173 if (getrusage(RUSAGE_LWP, &ru) == 0) return MakeTime(ru);
174 DiagnoseAndExit("getrusage(RUSAGE_LWP, ...) failed");
175 #elif defined(CLOCK_THREAD_CPUTIME_ID)
176 struct timespec ts;
177 if (clock_gettime(CLOCK_THREAD_CPUTIME_ID, &ts) == 0) return MakeTime(ts);
178 DiagnoseAndExit("clock_gettime(CLOCK_THREAD_CPUTIME_ID, ...) failed");
179 #else
180 #error Per-thread timing is not available on your system.
181 #endif
184 std::string LocalDateTimeString() {
185 // Write the local time in RFC3339 format yyyy-mm-ddTHH:MM:SS+/-HH:MM.
186 typedef std::chrono::system_clock Clock;
187 std::time_t now = Clock::to_time_t(Clock::now());
188 const std::size_t kTzOffsetLen = 6;
189 const std::size_t kTimestampLen = 19;
191 std::size_t tz_len;
192 std::size_t timestamp_len;
193 long int offset_minutes;
194 char tz_offset_sign = '+';
195 // tz_offset is set in one of three ways:
196 // * strftime with %z - This either returns empty or the ISO 8601 time. The
197 // maximum length an
198 // ISO 8601 string can be is 7 (e.g. -03:30, plus trailing zero).
199 // * snprintf with %c%02li:%02li - The maximum length is 41 (one for %c, up to
200 // 19 for %02li,
201 // one for :, up to 19 %02li, plus trailing zero).
202 // * A fixed string of "-00:00". The maximum length is 7 (-00:00, plus
203 // trailing zero).
205 // Thus, the maximum size this needs to be is 41.
206 char tz_offset[41];
207 // Long enough buffer to avoid format-overflow warnings
208 char storage[128];
210 #if defined(BENCHMARK_OS_WINDOWS)
211 std::tm* timeinfo_p = ::localtime(&now);
212 #else
213 std::tm timeinfo;
214 std::tm* timeinfo_p = &timeinfo;
215 ::localtime_r(&now, &timeinfo);
216 #endif
218 tz_len = std::strftime(tz_offset, sizeof(tz_offset), "%z", timeinfo_p);
220 if (tz_len < kTzOffsetLen && tz_len > 1) {
221 // Timezone offset was written. strftime writes offset as +HHMM or -HHMM,
222 // RFC3339 specifies an offset as +HH:MM or -HH:MM. To convert, we parse
223 // the offset as an integer, then reprint it to a string.
225 offset_minutes = ::strtol(tz_offset, NULL, 10);
226 if (offset_minutes < 0) {
227 offset_minutes *= -1;
228 tz_offset_sign = '-';
231 tz_len =
232 ::snprintf(tz_offset, sizeof(tz_offset), "%c%02li:%02li",
233 tz_offset_sign, offset_minutes / 100, offset_minutes % 100);
234 BM_CHECK(tz_len == kTzOffsetLen);
235 ((void)tz_len); // Prevent unused variable warning in optimized build.
236 } else {
237 // Unknown offset. RFC3339 specifies that unknown local offsets should be
238 // written as UTC time with -00:00 timezone.
239 #if defined(BENCHMARK_OS_WINDOWS)
240 // Potential race condition if another thread calls localtime or gmtime.
241 timeinfo_p = ::gmtime(&now);
242 #else
243 ::gmtime_r(&now, &timeinfo);
244 #endif
246 strncpy(tz_offset, "-00:00", kTzOffsetLen + 1);
249 timestamp_len =
250 std::strftime(storage, sizeof(storage), "%Y-%m-%dT%H:%M:%S", timeinfo_p);
251 BM_CHECK(timestamp_len == kTimestampLen);
252 // Prevent unused variable warning in optimized build.
253 ((void)kTimestampLen);
255 std::strncat(storage, tz_offset, sizeof(storage) - timestamp_len - 1);
256 return std::string(storage);
259 } // end namespace benchmark