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#if defined(_MSC_VER)
16// FIXME: This must be defined before any other includes to disable deprecation
17// warnings for use of codecvt from C++17. We should remove our reliance on
18// the deprecated functionality instead.
19#define _SILENCE_CXX17_CODECVT_HEADER_DEPRECATION_WARNING
20#endif
21
22#include "internal_macros.h"
23
24#ifdef BENCHMARK_OS_WINDOWS
25#if !defined(WINVER) || WINVER < 0x0600
26#undef WINVER
27#define WINVER 0x0600
28#endif // WINVER handling
29#include <shlwapi.h>
30#undef StrCat // Don't let StrCat in string_util.h be renamed to lstrcatA
31#include <versionhelpers.h>
32#include <windows.h>
33
34#include <codecvt>
35#else
36#include <fcntl.h>
37#if !defined(BENCHMARK_OS_FUCHSIA) && !defined(BENCHMARK_OS_QURT)
38#include <sys/resource.h>
39#endif
40#include <sys/time.h>
41#include <sys/types.h> // this header must be included before 'sys/sysctl.h' to avoid compilation error on FreeBSD
42#include <unistd.h>
43#if defined BENCHMARK_OS_FREEBSD || defined BENCHMARK_OS_MACOSX || \
44 defined BENCHMARK_OS_NETBSD || defined BENCHMARK_OS_OPENBSD || \
45 defined BENCHMARK_OS_DRAGONFLY
46#define BENCHMARK_HAS_SYSCTL
47#include <sys/sysctl.h>
48#endif
49#endif
50#if defined(BENCHMARK_OS_SOLARIS)
51#include <kstat.h>
52#include <netdb.h>
53#endif
54#if defined(BENCHMARK_OS_QNX)
55#include <sys/syspage.h>
56#endif
57#if defined(BENCHMARK_OS_QURT)
58#include <qurt.h>
59#endif
60#if defined(BENCHMARK_HAS_PTHREAD_AFFINITY)
61#include <pthread.h>
62#endif
63
64#include <algorithm>
65#include <array>
66#include <bitset>
67#include <cerrno>
68#include <climits>
69#include <cstdint>
70#include <cstdio>
71#include <cstdlib>
72#include <cstring>
73#include <fstream>
74#include <iostream>
75#include <iterator>
76#include <limits>
77#include <locale>
78#include <memory>
79#include <random>
80#include <sstream>
81#include <utility>
82
83#include "benchmark/benchmark.h"
84#include "check.h"
85#include "cycleclock.h"
86#include "internal_macros.h"
87#include "log.h"
88#include "string_util.h"
89#include "timers.h"
90
91namespace benchmark {
92namespace {
93
94void PrintImp(std::ostream& out) { out << std::endl; }
95
96template <class First, class... Rest>
97void PrintImp(std::ostream& out, First&& f, Rest&&... rest) {
98 out << std::forward<First>(f);
99 PrintImp(out, std::forward<Rest>(rest)...);
100}
101
102template <class... Args>
103BENCHMARK_NORETURN void PrintErrorAndDie(Args&&... args) {
104 PrintImp(std::cerr, std::forward<Args>(args)...);
105 std::exit(EXIT_FAILURE);
106}
107
108#ifdef BENCHMARK_HAS_SYSCTL
109
110/// ValueUnion - A type used to correctly alias the byte-for-byte output of
111/// `sysctl` with the result type it's to be interpreted as.
112struct ValueUnion {
113 union DataT {
114 int32_t int32_value;
115 int64_t int64_value;
116 // For correct aliasing of union members from bytes.
117 char bytes[8];
118 };
119 using DataPtr = std::unique_ptr<DataT, decltype(&std::free)>;
120
121 // The size of the data union member + its trailing array size.
122 std::size_t size;
123 DataPtr buff;
124
125 public:
126 ValueUnion() : size(0), buff(nullptr, &std::free) {}
127
128 explicit ValueUnion(std::size_t buff_size)
129 : size(sizeof(DataT) + buff_size),
130 buff(::new (std::malloc(size)) DataT(), &std::free) {}
131
132 ValueUnion(ValueUnion&& other) = default;
133
134 explicit operator bool() const { return bool(buff); }
135
136 char* data() const { return buff->bytes; }
137
138 std::string GetAsString() const { return std::string(data()); }
139
140 int64_t GetAsInteger() const {
141 if (size == sizeof(buff->int32_value))
142 return buff->int32_value;
143 else if (size == sizeof(buff->int64_value))
144 return buff->int64_value;
145 BENCHMARK_UNREACHABLE();
146 }
147
148 template <class T, int N>
149 std::array<T, N> GetAsArray() {
150 const int arr_size = sizeof(T) * N;
151 BM_CHECK_LE(arr_size, size);
152 std::array<T, N> arr;
153 std::memcpy(arr.data(), data(), arr_size);
154 return arr;
155 }
156};
157
158ValueUnion GetSysctlImp(std::string const& name) {
159#if defined BENCHMARK_OS_OPENBSD
160 int mib[2];
161
162 mib[0] = CTL_HW;
163 if ((name == "hw.ncpuonline") || (name == "hw.cpuspeed")) {
164 ValueUnion buff(sizeof(int));
165
166 if (name == "hw.ncpuonline") {
167 mib[1] = HW_NCPUONLINE;
168 } else {
169 mib[1] = HW_CPUSPEED;
170 }
171
172 if (sysctl(mib, 2, buff.data(), &buff.size, nullptr, 0) == -1) {
173 return ValueUnion();
174 }
175 return buff;
176 }
177 return ValueUnion();
178#else
179 std::size_t cur_buff_size = 0;
180 if (sysctlbyname(name.c_str(), nullptr, &cur_buff_size, nullptr, 0) == -1)
181 return ValueUnion();
182
183 ValueUnion buff(cur_buff_size);
184 if (sysctlbyname(name.c_str(), buff.data(), &buff.size, nullptr, 0) == 0)
185 return buff;
186 return ValueUnion();
187#endif
188}
189
190BENCHMARK_MAYBE_UNUSED
191bool GetSysctl(std::string const& name, std::string* out) {
192 out->clear();
193 auto buff = GetSysctlImp(name);
194 if (!buff) return false;
195 out->assign(buff.data());
196 return true;
197}
198
199template <class Tp,
200 class = typename std::enable_if<std::is_integral<Tp>::value>::type>
201bool GetSysctl(std::string const& name, Tp* out) {
202 *out = 0;
203 auto buff = GetSysctlImp(name);
204 if (!buff) return false;
205 *out = static_cast<Tp>(buff.GetAsInteger());
206 return true;
207}
208
209template <class Tp, size_t N>
210bool GetSysctl(std::string const& name, std::array<Tp, N>* out) {
211 auto buff = GetSysctlImp(name);
212 if (!buff) return false;
213 *out = buff.GetAsArray<Tp, N>();
214 return true;
215}
216#endif
217
218template <class ArgT>
219bool ReadFromFile(std::string const& fname, ArgT* arg) {
220 *arg = ArgT();
221 std::ifstream f(fname.c_str());
222 if (!f.is_open()) return false;
223 f >> *arg;
224 return f.good();
225}
226
227CPUInfo::Scaling CpuScaling(int num_cpus) {
228 // We don't have a valid CPU count, so don't even bother.
229 if (num_cpus <= 0) return CPUInfo::Scaling::UNKNOWN;
230#if defined(BENCHMARK_OS_QNX)
231 return CPUInfo::Scaling::UNKNOWN;
232#elif !defined(BENCHMARK_OS_WINDOWS)
233 // On Linux, the CPUfreq subsystem exposes CPU information as files on the
234 // local file system. If reading the exported files fails, then we may not be
235 // running on Linux, so we silently ignore all the read errors.
236 std::string res;
237 for (int cpu = 0; cpu < num_cpus; ++cpu) {
238 std::string governor_file =
239 StrCat(args: "/sys/devices/system/cpu/cpu", args&: cpu, args: "/cpufreq/scaling_governor");
240 if (ReadFromFile(fname: governor_file, arg: &res) && res != "performance")
241 return CPUInfo::Scaling::ENABLED;
242 }
243 return CPUInfo::Scaling::DISABLED;
244#else
245 return CPUInfo::Scaling::UNKNOWN;
246#endif
247}
248
249int CountSetBitsInCPUMap(std::string val) {
250 auto CountBits = [](std::string part) {
251 using CPUMask = std::bitset<sizeof(std::uintptr_t) * CHAR_BIT>;
252 part = "0x" + part;
253 CPUMask mask(benchmark::stoul(str: part, idx: nullptr, base: 16));
254 return static_cast<int>(mask.count());
255 };
256 std::size_t pos;
257 int total = 0;
258 while ((pos = val.find(c: ',')) != std::string::npos) {
259 total += CountBits(val.substr(pos: 0, n: pos));
260 val = val.substr(pos: pos + 1);
261 }
262 if (!val.empty()) {
263 total += CountBits(val);
264 }
265 return total;
266}
267
268BENCHMARK_MAYBE_UNUSED
269std::vector<CPUInfo::CacheInfo> GetCacheSizesFromKVFS() {
270 std::vector<CPUInfo::CacheInfo> res;
271 std::string dir = "/sys/devices/system/cpu/cpu0/cache/";
272 int idx = 0;
273 while (true) {
274 CPUInfo::CacheInfo info;
275 std::string fpath = StrCat(args&: dir, args: "index", args: idx++, args: "/");
276 std::ifstream f(StrCat(args&: fpath, args: "size").c_str());
277 if (!f.is_open()) break;
278 std::string suffix;
279 f >> info.size;
280 if (f.fail())
281 PrintErrorAndDie(args: "Failed while reading file '", args&: fpath, args: "size'");
282 if (f.good()) {
283 f >> suffix;
284 if (f.bad())
285 PrintErrorAndDie(
286 args: "Invalid cache size format: failed to read size suffix");
287 else if (f && suffix != "K")
288 PrintErrorAndDie(args: "Invalid cache size format: Expected bytes ", args&: suffix);
289 else if (suffix == "K")
290 info.size *= 1024;
291 }
292 if (!ReadFromFile(fname: StrCat(args&: fpath, args: "type"), arg: &info.type))
293 PrintErrorAndDie(args: "Failed to read from file ", args&: fpath, args: "type");
294 if (!ReadFromFile(fname: StrCat(args&: fpath, args: "level"), arg: &info.level))
295 PrintErrorAndDie(args: "Failed to read from file ", args&: fpath, args: "level");
296 std::string map_str;
297 if (!ReadFromFile(fname: StrCat(args&: fpath, args: "shared_cpu_map"), arg: &map_str))
298 PrintErrorAndDie(args: "Failed to read from file ", args&: fpath, args: "shared_cpu_map");
299 info.num_sharing = CountSetBitsInCPUMap(val: map_str);
300 res.push_back(x: info);
301 }
302
303 return res;
304}
305
306#ifdef BENCHMARK_OS_MACOSX
307std::vector<CPUInfo::CacheInfo> GetCacheSizesMacOSX() {
308 std::vector<CPUInfo::CacheInfo> res;
309 std::array<int, 4> cache_counts{{0, 0, 0, 0}};
310 GetSysctl("hw.cacheconfig", &cache_counts);
311
312 struct {
313 std::string name;
314 std::string type;
315 int level;
316 int num_sharing;
317 } cases[] = {{"hw.l1dcachesize", "Data", 1, cache_counts[1]},
318 {"hw.l1icachesize", "Instruction", 1, cache_counts[1]},
319 {"hw.l2cachesize", "Unified", 2, cache_counts[2]},
320 {"hw.l3cachesize", "Unified", 3, cache_counts[3]}};
321 for (auto& c : cases) {
322 int val;
323 if (!GetSysctl(c.name, &val)) continue;
324 CPUInfo::CacheInfo info;
325 info.type = c.type;
326 info.level = c.level;
327 info.size = val;
328 info.num_sharing = c.num_sharing;
329 res.push_back(std::move(info));
330 }
331 return res;
332}
333#elif defined(BENCHMARK_OS_WINDOWS)
334std::vector<CPUInfo::CacheInfo> GetCacheSizesWindows() {
335 std::vector<CPUInfo::CacheInfo> res;
336 DWORD buffer_size = 0;
337 using PInfo = SYSTEM_LOGICAL_PROCESSOR_INFORMATION;
338 using CInfo = CACHE_DESCRIPTOR;
339
340 using UPtr = std::unique_ptr<PInfo, decltype(&std::free)>;
341 GetLogicalProcessorInformation(nullptr, &buffer_size);
342 UPtr buff(static_cast<PInfo*>(std::malloc(buffer_size)), &std::free);
343 if (!GetLogicalProcessorInformation(buff.get(), &buffer_size))
344 PrintErrorAndDie("Failed during call to GetLogicalProcessorInformation: ",
345 GetLastError());
346
347 PInfo* it = buff.get();
348 PInfo* end = buff.get() + (buffer_size / sizeof(PInfo));
349
350 for (; it != end; ++it) {
351 if (it->Relationship != RelationCache) continue;
352 using BitSet = std::bitset<sizeof(ULONG_PTR) * CHAR_BIT>;
353 BitSet b(it->ProcessorMask);
354 // To prevent duplicates, only consider caches where CPU 0 is specified
355 if (!b.test(0)) continue;
356 const CInfo& cache = it->Cache;
357 CPUInfo::CacheInfo C;
358 C.num_sharing = static_cast<int>(b.count());
359 C.level = cache.Level;
360 C.size = cache.Size;
361 C.type = "Unknown";
362 switch (cache.Type) {
363 case CacheUnified:
364 C.type = "Unified";
365 break;
366 case CacheInstruction:
367 C.type = "Instruction";
368 break;
369 case CacheData:
370 C.type = "Data";
371 break;
372 case CacheTrace:
373 C.type = "Trace";
374 break;
375 }
376 res.push_back(C);
377 }
378 return res;
379}
380#elif BENCHMARK_OS_QNX
381std::vector<CPUInfo::CacheInfo> GetCacheSizesQNX() {
382 std::vector<CPUInfo::CacheInfo> res;
383 struct cacheattr_entry* cache = SYSPAGE_ENTRY(cacheattr);
384 uint32_t const elsize = SYSPAGE_ELEMENT_SIZE(cacheattr);
385 int num = SYSPAGE_ENTRY_SIZE(cacheattr) / elsize;
386 for (int i = 0; i < num; ++i) {
387 CPUInfo::CacheInfo info;
388 switch (cache->flags) {
389 case CACHE_FLAG_INSTR:
390 info.type = "Instruction";
391 info.level = 1;
392 break;
393 case CACHE_FLAG_DATA:
394 info.type = "Data";
395 info.level = 1;
396 break;
397 case CACHE_FLAG_UNIFIED:
398 info.type = "Unified";
399 info.level = 2;
400 break;
401 case CACHE_FLAG_SHARED:
402 info.type = "Shared";
403 info.level = 3;
404 break;
405 default:
406 continue;
407 break;
408 }
409 info.size = cache->line_size * cache->num_lines;
410 info.num_sharing = 0;
411 res.push_back(std::move(info));
412 cache = SYSPAGE_ARRAY_ADJ_OFFSET(cacheattr, cache, elsize);
413 }
414 return res;
415}
416#endif
417
418std::vector<CPUInfo::CacheInfo> GetCacheSizes() {
419#ifdef BENCHMARK_OS_MACOSX
420 return GetCacheSizesMacOSX();
421#elif defined(BENCHMARK_OS_WINDOWS)
422 return GetCacheSizesWindows();
423#elif defined(BENCHMARK_OS_QNX)
424 return GetCacheSizesQNX();
425#elif defined(BENCHMARK_OS_QURT)
426 return std::vector<CPUInfo::CacheInfo>();
427#else
428 return GetCacheSizesFromKVFS();
429#endif
430}
431
432std::string GetSystemName() {
433#if defined(BENCHMARK_OS_WINDOWS)
434 std::string str;
435 static constexpr int COUNT = MAX_COMPUTERNAME_LENGTH + 1;
436 TCHAR hostname[COUNT] = {'\0'};
437 DWORD DWCOUNT = COUNT;
438 if (!GetComputerName(hostname, &DWCOUNT)) return std::string("");
439#ifndef UNICODE
440 str = std::string(hostname, DWCOUNT);
441#else
442 // `WideCharToMultiByte` returns `0` when conversion fails.
443 int len = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, hostname,
444 DWCOUNT, NULL, 0, NULL, NULL);
445 str.resize(len);
446 WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, hostname, DWCOUNT, &str[0],
447 str.size(), NULL, NULL);
448#endif
449 return str;
450#elif defined(BENCHMARK_OS_QURT)
451 std::string str = "Hexagon DSP";
452 qurt_arch_version_t arch_version_struct;
453 if (qurt_sysenv_get_arch_version(&arch_version_struct) == QURT_EOK) {
454 str += " v";
455 str += std::to_string(arch_version_struct.arch_version);
456 }
457 return str;
458#else
459#ifndef HOST_NAME_MAX
460#ifdef BENCHMARK_HAS_SYSCTL // BSD/Mac doesn't have HOST_NAME_MAX defined
461#define HOST_NAME_MAX 64
462#elif defined(BENCHMARK_OS_NACL)
463#define HOST_NAME_MAX 64
464#elif defined(BENCHMARK_OS_QNX)
465#define HOST_NAME_MAX 154
466#elif defined(BENCHMARK_OS_RTEMS)
467#define HOST_NAME_MAX 256
468#elif defined(BENCHMARK_OS_SOLARIS)
469#define HOST_NAME_MAX MAXHOSTNAMELEN
470#elif defined(BENCHMARK_OS_ZOS)
471#define HOST_NAME_MAX _POSIX_HOST_NAME_MAX
472#else
473#pragma message("HOST_NAME_MAX not defined. using 64")
474#define HOST_NAME_MAX 64
475#endif
476#endif // def HOST_NAME_MAX
477 char hostname[HOST_NAME_MAX];
478 int retVal = gethostname(name: hostname, HOST_NAME_MAX);
479 if (retVal != 0) return std::string("");
480 return std::string(hostname);
481#endif // Catch-all POSIX block.
482}
483
484int GetNumCPUsImpl() {
485#ifdef BENCHMARK_OS_WINDOWS
486 SYSTEM_INFO sysinfo;
487 // Use memset as opposed to = {} to avoid GCC missing initializer false
488 // positives.
489 std::memset(&sysinfo, 0, sizeof(SYSTEM_INFO));
490 GetSystemInfo(&sysinfo);
491 // number of logical processors in the current group
492 return static_cast<int>(sysinfo.dwNumberOfProcessors);
493#elif defined(BENCHMARK_OS_QNX)
494 return static_cast<int>(_syspage_ptr->num_cpu);
495#elif defined(BENCHMARK_OS_QURT)
496 qurt_sysenv_max_hthreads_t hardware_threads;
497 if (qurt_sysenv_get_max_hw_threads(&hardware_threads) != QURT_EOK) {
498 hardware_threads.max_hthreads = 1;
499 }
500 return hardware_threads.max_hthreads;
501#elif defined(BENCHMARK_HAS_SYSCTL)
502 int num_cpu = -1;
503 constexpr auto* hwncpu =
504#if defined BENCHMARK_OS_MACOSX
505 "hw.logicalcpu";
506#elif defined(HW_NCPUONLINE)
507 "hw.ncpuonline";
508#else
509 "hw.ncpu";
510#endif
511 if (GetSysctl(hwncpu, &num_cpu)) return num_cpu;
512 PrintErrorAndDie("Err: ", strerror(errno));
513#elif defined(_SC_NPROCESSORS_ONLN)
514 // Returns -1 in case of a failure.
515 int num_cpu = static_cast<int>(sysconf(_SC_NPROCESSORS_ONLN));
516 if (num_cpu < 0) {
517 PrintErrorAndDie(args: "sysconf(_SC_NPROCESSORS_ONLN) failed with error: ",
518 args: strerror(errno));
519 }
520 return num_cpu;
521#endif
522 BENCHMARK_UNREACHABLE();
523}
524
525int GetNumCPUs() {
526 int num_cpus = GetNumCPUsImpl();
527 if (num_cpus < 1) {
528 std::cerr << "Unable to extract number of CPUs.\n";
529 /* There is at least one CPU which we run on. */
530 num_cpus = 1;
531 }
532 return num_cpus;
533}
534
535class ThreadAffinityGuard final {
536 public:
537 ThreadAffinityGuard() : reset_affinity(SetAffinity()) {
538 if (!reset_affinity)
539 std::cerr << "***WARNING*** Failed to set thread affinity. Estimated CPU "
540 "frequency may be incorrect."
541 << std::endl;
542 }
543
544 ~ThreadAffinityGuard() {
545 if (!reset_affinity) return;
546
547#if defined(BENCHMARK_HAS_PTHREAD_AFFINITY)
548 int ret = pthread_setaffinity_np(th: self, cpusetsize: sizeof(previous_affinity),
549 cpuset: &previous_affinity);
550 if (ret == 0) return;
551#elif defined(BENCHMARK_OS_WINDOWS_WIN32)
552 DWORD_PTR ret = SetThreadAffinityMask(self, previous_affinity);
553 if (ret != 0) return;
554#endif // def BENCHMARK_HAS_PTHREAD_AFFINITY
555 PrintErrorAndDie(args: "Failed to reset thread affinity");
556 }
557
558 ThreadAffinityGuard(ThreadAffinityGuard&&) = delete;
559 ThreadAffinityGuard(const ThreadAffinityGuard&) = delete;
560 ThreadAffinityGuard& operator=(ThreadAffinityGuard&&) = delete;
561 ThreadAffinityGuard& operator=(const ThreadAffinityGuard&) = delete;
562
563 private:
564 bool SetAffinity() {
565#if defined(BENCHMARK_HAS_PTHREAD_AFFINITY)
566 int ret;
567 self = pthread_self();
568 ret = pthread_getaffinity_np(th: self, cpusetsize: sizeof(previous_affinity),
569 cpuset: &previous_affinity);
570 if (ret != 0) return false;
571
572 cpu_set_t affinity;
573 memcpy(dest: &affinity, src: &previous_affinity, n: sizeof(affinity));
574
575 bool is_first_cpu = true;
576
577 for (int i = 0; i < CPU_SETSIZE; ++i)
578 if (CPU_ISSET(i, &affinity)) {
579 if (is_first_cpu)
580 is_first_cpu = false;
581 else
582 CPU_CLR(i, &affinity);
583 }
584
585 if (is_first_cpu) return false;
586
587 ret = pthread_setaffinity_np(th: self, cpusetsize: sizeof(affinity), cpuset: &affinity);
588 return ret == 0;
589#elif defined(BENCHMARK_OS_WINDOWS_WIN32)
590 self = GetCurrentThread();
591 DWORD_PTR mask = static_cast<DWORD_PTR>(1) << GetCurrentProcessorNumber();
592 previous_affinity = SetThreadAffinityMask(self, mask);
593 return previous_affinity != 0;
594#else
595 return false;
596#endif // def BENCHMARK_HAS_PTHREAD_AFFINITY
597 }
598
599#if defined(BENCHMARK_HAS_PTHREAD_AFFINITY)
600 pthread_t self;
601 cpu_set_t previous_affinity;
602#elif defined(BENCHMARK_OS_WINDOWS_WIN32)
603 HANDLE self;
604 DWORD_PTR previous_affinity;
605#endif // def BENCHMARK_HAS_PTHREAD_AFFINITY
606 bool reset_affinity;
607};
608
609double GetCPUCyclesPerSecond(CPUInfo::Scaling scaling) {
610 // Currently, scaling is only used on linux path here,
611 // suppress diagnostics about it being unused on other paths.
612 (void)scaling;
613
614#if defined BENCHMARK_OS_LINUX || defined BENCHMARK_OS_CYGWIN
615 long freq;
616
617 // If the kernel is exporting the tsc frequency use that. There are issues
618 // where cpuinfo_max_freq cannot be relied on because the BIOS may be
619 // exporintg an invalid p-state (on x86) or p-states may be used to put the
620 // processor in a new mode (turbo mode). Essentially, those frequencies
621 // cannot always be relied upon. The same reasons apply to /proc/cpuinfo as
622 // well.
623 if (ReadFromFile(fname: "/sys/devices/system/cpu/cpu0/tsc_freq_khz", arg: &freq)
624 // If CPU scaling is disabled, use the *current* frequency.
625 // Note that we specifically don't want to read cpuinfo_cur_freq,
626 // because it is only readable by root.
627 || (scaling == CPUInfo::Scaling::DISABLED &&
628 ReadFromFile(fname: "/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq",
629 arg: &freq))
630 // Otherwise, if CPU scaling may be in effect, we want to use
631 // the *maximum* frequency, not whatever CPU speed some random processor
632 // happens to be using now.
633 || ReadFromFile(fname: "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq",
634 arg: &freq)) {
635 // The value is in kHz (as the file name suggests). For example, on a
636 // 2GHz warpstation, the file contains the value "2000000".
637 return static_cast<double>(freq) * 1000.0;
638 }
639
640 const double error_value = -1;
641 double bogo_clock = error_value;
642
643 std::ifstream f("/proc/cpuinfo");
644 if (!f.is_open()) {
645 std::cerr << "failed to open /proc/cpuinfo\n";
646 return error_value;
647 }
648
649 auto StartsWithKey = [](std::string const& Value, std::string const& Key) {
650 if (Key.size() > Value.size()) return false;
651 auto Cmp = [&](char X, char Y) {
652 return std::tolower(c: X) == std::tolower(c: Y);
653 };
654 return std::equal(first1: Key.begin(), last1: Key.end(), first2: Value.begin(), binary_pred: Cmp);
655 };
656
657 std::string ln;
658 while (std::getline(is&: f, str&: ln)) {
659 if (ln.empty()) continue;
660 std::size_t split_idx = ln.find(c: ':');
661 std::string value;
662 if (split_idx != std::string::npos) value = ln.substr(pos: split_idx + 1);
663 // When parsing the "cpu MHz" and "bogomips" (fallback) entries, we only
664 // accept positive values. Some environments (virtual machines) report zero,
665 // which would cause infinite looping in WallTime_Init.
666 if (StartsWithKey(ln, "cpu MHz")) {
667 if (!value.empty()) {
668 double cycles_per_second = benchmark::stod(str: value) * 1000000.0;
669 if (cycles_per_second > 0) return cycles_per_second;
670 }
671 } else if (StartsWithKey(ln, "bogomips")) {
672 if (!value.empty()) {
673 bogo_clock = benchmark::stod(str: value) * 1000000.0;
674 if (bogo_clock < 0.0) bogo_clock = error_value;
675 }
676 }
677 }
678 if (f.bad()) {
679 std::cerr << "Failure reading /proc/cpuinfo\n";
680 return error_value;
681 }
682 if (!f.eof()) {
683 std::cerr << "Failed to read to end of /proc/cpuinfo\n";
684 return error_value;
685 }
686 f.close();
687 // If we found the bogomips clock, but nothing better, we'll use it (but
688 // we're not happy about it); otherwise, fallback to the rough estimation
689 // below.
690 if (bogo_clock >= 0.0) return bogo_clock;
691
692#elif defined BENCHMARK_HAS_SYSCTL
693 constexpr auto* freqStr =
694#if defined(BENCHMARK_OS_FREEBSD) || defined(BENCHMARK_OS_NETBSD)
695 "machdep.tsc_freq";
696#elif defined BENCHMARK_OS_OPENBSD
697 "hw.cpuspeed";
698#elif defined BENCHMARK_OS_DRAGONFLY
699 "hw.tsc_frequency";
700#else
701 "hw.cpufrequency";
702#endif
703 unsigned long long hz = 0;
704#if defined BENCHMARK_OS_OPENBSD
705 if (GetSysctl(freqStr, &hz)) return static_cast<double>(hz * 1000000);
706#else
707 if (GetSysctl(freqStr, &hz)) return hz;
708#endif
709 fprintf(stderr, "Unable to determine clock rate from sysctl: %s: %s\n",
710 freqStr, strerror(errno));
711 fprintf(stderr,
712 "This does not affect benchmark measurements, only the "
713 "metadata output.\n");
714
715#elif defined BENCHMARK_OS_WINDOWS_WIN32
716 // In NT, read MHz from the registry. If we fail to do so or we're in win9x
717 // then make a crude estimate.
718 DWORD data, data_size = sizeof(data);
719 if (IsWindowsXPOrGreater() &&
720 SUCCEEDED(
721 SHGetValueA(HKEY_LOCAL_MACHINE,
722 "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
723 "~MHz", nullptr, &data, &data_size)))
724 return static_cast<double>(static_cast<int64_t>(data) *
725 static_cast<int64_t>(1000 * 1000)); // was mhz
726#elif defined(BENCHMARK_OS_SOLARIS)
727 kstat_ctl_t* kc = kstat_open();
728 if (!kc) {
729 std::cerr << "failed to open /dev/kstat\n";
730 return -1;
731 }
732 kstat_t* ksp = kstat_lookup(kc, const_cast<char*>("cpu_info"), -1,
733 const_cast<char*>("cpu_info0"));
734 if (!ksp) {
735 std::cerr << "failed to lookup in /dev/kstat\n";
736 return -1;
737 }
738 if (kstat_read(kc, ksp, NULL) < 0) {
739 std::cerr << "failed to read from /dev/kstat\n";
740 return -1;
741 }
742 kstat_named_t* knp = (kstat_named_t*)kstat_data_lookup(
743 ksp, const_cast<char*>("current_clock_Hz"));
744 if (!knp) {
745 std::cerr << "failed to lookup data in /dev/kstat\n";
746 return -1;
747 }
748 if (knp->data_type != KSTAT_DATA_UINT64) {
749 std::cerr << "current_clock_Hz is of unexpected data type: "
750 << knp->data_type << "\n";
751 return -1;
752 }
753 double clock_hz = knp->value.ui64;
754 kstat_close(kc);
755 return clock_hz;
756#elif defined(BENCHMARK_OS_QNX)
757 return static_cast<double>(
758 static_cast<int64_t>(SYSPAGE_ENTRY(cpuinfo)->speed) *
759 static_cast<int64_t>(1000 * 1000));
760#elif defined(BENCHMARK_OS_QURT)
761 // QuRT doesn't provide any API to query Hexagon frequency.
762 return 1000000000;
763#endif
764 // If we've fallen through, attempt to roughly estimate the CPU clock rate.
765
766 // Make sure to use the same cycle counter when starting and stopping the
767 // cycle timer. We just pin the current thread to a cpu in the previous
768 // affinity set.
769 ThreadAffinityGuard affinity_guard;
770
771 static constexpr double estimate_time_s = 1.0;
772 const double start_time = ChronoClockNow();
773 const auto start_ticks = cycleclock::Now();
774
775 // Impose load instead of calling sleep() to make sure the cycle counter
776 // works.
777 using PRNG = std::minstd_rand;
778 using Result = PRNG::result_type;
779 PRNG rng(static_cast<Result>(start_ticks));
780
781 Result state = 0;
782
783 do {
784 static constexpr size_t batch_size = 10000;
785 rng.discard(z: batch_size);
786 state += rng();
787
788 } while (ChronoClockNow() - start_time < estimate_time_s);
789
790 DoNotOptimize(value&: state);
791
792 const auto end_ticks = cycleclock::Now();
793 const double end_time = ChronoClockNow();
794
795 return static_cast<double>(end_ticks - start_ticks) / (end_time - start_time);
796 // Reset the affinity of current thread when the lifetime of affinity_guard
797 // ends.
798}
799
800std::vector<double> GetLoadAvg() {
801#if (defined BENCHMARK_OS_FREEBSD || defined(BENCHMARK_OS_LINUX) || \
802 defined BENCHMARK_OS_MACOSX || defined BENCHMARK_OS_NETBSD || \
803 defined BENCHMARK_OS_OPENBSD || defined BENCHMARK_OS_DRAGONFLY) && \
804 !(defined(__ANDROID__) && __ANDROID_API__ < 29)
805 static constexpr int kMaxSamples = 3;
806 std::vector<double> res(kMaxSamples, 0.0);
807 const int nelem = getloadavg(loadavg: res.data(), nelem: kMaxSamples);
808 if (nelem < 1) {
809 res.clear();
810 } else {
811 res.resize(new_size: nelem);
812 }
813 return res;
814#else
815 return {};
816#endif
817}
818
819} // end namespace
820
821const CPUInfo& CPUInfo::Get() {
822 static const CPUInfo* info = new CPUInfo();
823 return *info;
824}
825
826CPUInfo::CPUInfo()
827 : num_cpus(GetNumCPUs()),
828 scaling(CpuScaling(num_cpus)),
829 cycles_per_second(GetCPUCyclesPerSecond(scaling)),
830 caches(GetCacheSizes()),
831 load_avg(GetLoadAvg()) {}
832
833const SystemInfo& SystemInfo::Get() {
834 static const SystemInfo* info = new SystemInfo();
835 return *info;
836}
837
838SystemInfo::SystemInfo() : name(GetSystemName()) {}
839} // end namespace benchmark
840

Provided by KDAB

Privacy Policy
Improve your Profiling and Debugging skills
Find out more

source code of third-party/benchmark/src/sysinfo.cc