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