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 #include "internal_macros.h"
17 
18 #ifdef BENCHMARK_OS_WINDOWS
19 #include <shlwapi.h>
20 #undef StrCat  // Don't let StrCat in string_util.h be renamed to lstrcatA
21 #include <versionhelpers.h>
22 #include <windows.h>
23 #else
24 #include <fcntl.h>
25 #ifndef BENCHMARK_OS_FUCHSIA
26 #include <sys/resource.h>
27 #endif
28 #include <sys/time.h>
29 #include <sys/types.h>  // this header must be included before 'sys/sysctl.h' to avoid compilation error on FreeBSD
30 #include <unistd.h>
31 #if defined BENCHMARK_OS_FREEBSD || defined BENCHMARK_OS_MACOSX
32 #include <sys/sysctl.h>
33 #endif
34 #if defined(BENCHMARK_OS_MACOSX)
35 #include <mach/mach_init.h>
36 #include <mach/mach_port.h>
37 #include <mach/thread_act.h>
38 #endif
39 #endif
40 
41 #ifdef BENCHMARK_OS_EMSCRIPTEN
42 #include <emscripten.h>
43 #endif
44 
45 #include <cerrno>
46 #include <cstdint>
47 #include <cstdio>
48 #include <cstdlib>
49 #include <cstring>
50 #include <ctime>
51 #include <iostream>
52 #include <limits>
53 #include <mutex>
54 
55 #include "check.h"
56 #include "log.h"
57 #include "sleep.h"
58 #include "string_util.h"
59 
60 namespace benchmark {
61 
62 // Suppress unused warnings on helper functions.
63 #if defined(__GNUC__)
64 #pragma GCC diagnostic ignored "-Wunused-function"
65 #endif
66 
67 namespace {
68 #if defined(BENCHMARK_OS_WINDOWS)
MakeTime(FILETIME const & kernel_time,FILETIME const & user_time)69 double MakeTime(FILETIME const& kernel_time, FILETIME const& user_time) {
70   ULARGE_INTEGER kernel;
71   ULARGE_INTEGER user;
72   kernel.HighPart = kernel_time.dwHighDateTime;
73   kernel.LowPart = kernel_time.dwLowDateTime;
74   user.HighPart = user_time.dwHighDateTime;
75   user.LowPart = user_time.dwLowDateTime;
76   return (static_cast<double>(kernel.QuadPart) +
77           static_cast<double>(user.QuadPart)) *
78          1e-7;
79 }
80 #elif !defined(BENCHMARK_OS_FUCHSIA)
81 double MakeTime(struct rusage const& ru) {
82   return (static_cast<double>(ru.ru_utime.tv_sec) +
83           static_cast<double>(ru.ru_utime.tv_usec) * 1e-6 +
84           static_cast<double>(ru.ru_stime.tv_sec) +
85           static_cast<double>(ru.ru_stime.tv_usec) * 1e-6);
86 }
87 #endif
88 #if defined(BENCHMARK_OS_MACOSX)
MakeTime(thread_basic_info_data_t const & info)89 double MakeTime(thread_basic_info_data_t const& info) {
90   return (static_cast<double>(info.user_time.seconds) +
91           static_cast<double>(info.user_time.microseconds) * 1e-6 +
92           static_cast<double>(info.system_time.seconds) +
93           static_cast<double>(info.system_time.microseconds) * 1e-6);
94 }
95 #endif
96 #if defined(CLOCK_PROCESS_CPUTIME_ID) || defined(CLOCK_THREAD_CPUTIME_ID)
MakeTime(struct timespec const & ts)97 double MakeTime(struct timespec const& ts) {
98   return ts.tv_sec + (static_cast<double>(ts.tv_nsec) * 1e-9);
99 }
100 #endif
101 
DiagnoseAndExit(const char * msg)102 BENCHMARK_NORETURN static void DiagnoseAndExit(const char* msg) {
103   std::cerr << "ERROR: " << msg << std::endl;
104   std::exit(EXIT_FAILURE);
105 }
106 
107 }  // end namespace
108 
ProcessCPUUsage()109 double ProcessCPUUsage() {
110 #if defined(BENCHMARK_OS_WINDOWS)
111   HANDLE proc = GetCurrentProcess();
112   FILETIME creation_time;
113   FILETIME exit_time;
114   FILETIME kernel_time;
115   FILETIME user_time;
116   if (GetProcessTimes(proc, &creation_time, &exit_time, &kernel_time,
117                       &user_time))
118     return MakeTime(kernel_time, user_time);
119   DiagnoseAndExit("GetProccessTimes() failed");
120 #elif defined(BENCHMARK_OS_EMSCRIPTEN)
121   // clock_gettime(CLOCK_PROCESS_CPUTIME_ID, ...) returns 0 on Emscripten.
122   // Use Emscripten-specific API. Reported CPU time would be exactly the
123   // same as total time, but this is ok because there aren't long-latency
124   // syncronous system calls in Emscripten.
125   return emscripten_get_now() * 1e-3;
126 #elif defined(CLOCK_PROCESS_CPUTIME_ID) && !defined(BENCHMARK_OS_MACOSX)
127   // FIXME We want to use clock_gettime, but its not available in MacOS 10.11. See
128   // https://github.com/google/benchmark/pull/292
129   struct timespec spec;
130   if (clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &spec) == 0)
131     return MakeTime(spec);
132   DiagnoseAndExit("clock_gettime(CLOCK_PROCESS_CPUTIME_ID, ...) failed");
133 #else
134   struct rusage ru;
135   if (getrusage(RUSAGE_SELF, &ru) == 0) return MakeTime(ru);
136   DiagnoseAndExit("getrusage(RUSAGE_SELF, ...) failed");
137 #endif
138 }
139 
ThreadCPUUsage()140 double ThreadCPUUsage() {
141 #if defined(BENCHMARK_OS_WINDOWS)
142   HANDLE this_thread = GetCurrentThread();
143   FILETIME creation_time;
144   FILETIME exit_time;
145   FILETIME kernel_time;
146   FILETIME user_time;
147   GetThreadTimes(this_thread, &creation_time, &exit_time, &kernel_time,
148                  &user_time);
149   return MakeTime(kernel_time, user_time);
150 #elif defined(BENCHMARK_OS_MACOSX)
151   // FIXME We want to use clock_gettime, but its not available in MacOS 10.11. See
152   // https://github.com/google/benchmark/pull/292
153   mach_msg_type_number_t count = THREAD_BASIC_INFO_COUNT;
154   thread_basic_info_data_t info;
155   mach_port_t thread = pthread_mach_thread_np(pthread_self());
156   if (thread_info(thread, THREAD_BASIC_INFO, (thread_info_t)&info, &count) ==
157       KERN_SUCCESS) {
158     return MakeTime(info);
159   }
160   DiagnoseAndExit("ThreadCPUUsage() failed when evaluating thread_info");
161 #elif defined(BENCHMARK_OS_EMSCRIPTEN)
162   // Emscripten doesn't support traditional threads
163   return ProcessCPUUsage();
164 #elif defined(BENCHMARK_OS_RTEMS)
165   // RTEMS doesn't support CLOCK_THREAD_CPUTIME_ID. See
166   // https://github.com/RTEMS/rtems/blob/master/cpukit/posix/src/clockgettime.c
167   return ProcessCPUUsage();
168 #elif defined(BENCHMARK_OS_SOLARIS)
169   struct rusage ru;
170   if (getrusage(RUSAGE_LWP, &ru) == 0) return MakeTime(ru);
171   DiagnoseAndExit("getrusage(RUSAGE_LWP, ...) failed");
172 #elif defined(CLOCK_THREAD_CPUTIME_ID)
173   struct timespec ts;
174   if (clock_gettime(CLOCK_THREAD_CPUTIME_ID, &ts) == 0) return MakeTime(ts);
175   DiagnoseAndExit("clock_gettime(CLOCK_THREAD_CPUTIME_ID, ...) failed");
176 #else
177 #error Per-thread timing is not available on your system.
178 #endif
179 }
180 
181 namespace {
182 
DateTimeString(bool local)183 std::string DateTimeString(bool local) {
184   typedef std::chrono::system_clock Clock;
185   std::time_t now = Clock::to_time_t(Clock::now());
186   const std::size_t kStorageSize = 128;
187   char storage[kStorageSize];
188   std::size_t written;
189 
190   if (local) {
191 #if defined(BENCHMARK_OS_WINDOWS)
192     written =
193         std::strftime(storage, sizeof(storage), "%x %X", ::localtime(&now));
194 #else
195     std::tm timeinfo;
196     ::localtime_r(&now, &timeinfo);
197     written = std::strftime(storage, sizeof(storage), "%F %T", &timeinfo);
198 #endif
199   } else {
200 #if defined(BENCHMARK_OS_WINDOWS)
201     written = std::strftime(storage, sizeof(storage), "%x %X", ::gmtime(&now));
202 #else
203     std::tm timeinfo;
204     ::gmtime_r(&now, &timeinfo);
205     written = std::strftime(storage, sizeof(storage), "%F %T", &timeinfo);
206 #endif
207   }
208   CHECK(written < kStorageSize);
209   ((void)written);  // prevent unused variable in optimized mode.
210   return std::string(storage);
211 }
212 
213 }  // end namespace
214 
LocalDateTimeString()215 std::string LocalDateTimeString() { return DateTimeString(true); }
216 
217 }  // end namespace benchmark
218