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