Skip to content

Commit fbe470c

Browse files
authored
[benchmark] Get number of CPUs with sysconf() on Linux (llvm#125603)
(cherry picked from commit c24774dc4f4402c3ad150363321cc972ed2669e7)
1 parent ce7bca7 commit fbe470c

File tree

1 file changed

+3
-50
lines changed

1 file changed

+3
-50
lines changed

third-party/benchmark/src/sysinfo.cc

+3-50
Original file line numberDiff line numberDiff line change
@@ -495,14 +495,14 @@ int GetNumCPUsImpl() {
495495
return sysinfo.dwNumberOfProcessors; // number of logical
496496
// processors in the current
497497
// group
498-
#elif defined(BENCHMARK_OS_SOLARIS)
498+
#elif defined(__linux__) || defined(BENCHMARK_OS_SOLARIS)
499499
// Returns -1 in case of a failure.
500-
long num_cpu = sysconf(_SC_NPROCESSORS_ONLN);
500+
int num_cpu = static_cast<int>(sysconf(_SC_NPROCESSORS_ONLN));
501501
if (num_cpu < 0) {
502502
PrintErrorAndDie("sysconf(_SC_NPROCESSORS_ONLN) failed with error: ",
503503
strerror(errno));
504504
}
505-
return (int)num_cpu;
505+
return num_cpu;
506506
#elif defined(BENCHMARK_OS_QNX)
507507
return static_cast<int>(_syspage_ptr->num_cpu);
508508
#elif defined(BENCHMARK_OS_QURT)
@@ -511,53 +511,6 @@ int GetNumCPUsImpl() {
511511
hardware_threads.max_hthreads = 1;
512512
}
513513
return hardware_threads.max_hthreads;
514-
#else
515-
int num_cpus = 0;
516-
int max_id = -1;
517-
std::ifstream f("/proc/cpuinfo");
518-
if (!f.is_open()) {
519-
PrintErrorAndDie("Failed to open /proc/cpuinfo");
520-
}
521-
#if defined(__alpha__)
522-
const std::string Key = "cpus detected";
523-
#else
524-
const std::string Key = "processor";
525-
#endif
526-
std::string ln;
527-
while (std::getline(f, ln)) {
528-
if (ln.empty()) continue;
529-
std::size_t split_idx = ln.find(':');
530-
std::string value;
531-
#if defined(__s390__)
532-
// s390 has another format in /proc/cpuinfo
533-
// it needs to be parsed differently
534-
if (split_idx != std::string::npos)
535-
value = ln.substr(Key.size() + 1, split_idx - Key.size() - 1);
536-
#else
537-
if (split_idx != std::string::npos) value = ln.substr(split_idx + 1);
538-
#endif
539-
if (ln.size() >= Key.size() && ln.compare(0, Key.size(), Key) == 0) {
540-
num_cpus++;
541-
if (!value.empty()) {
542-
const int cur_id = benchmark::stoi(value);
543-
max_id = std::max(cur_id, max_id);
544-
}
545-
}
546-
}
547-
if (f.bad()) {
548-
PrintErrorAndDie("Failure reading /proc/cpuinfo");
549-
}
550-
if (!f.eof()) {
551-
PrintErrorAndDie("Failed to read to end of /proc/cpuinfo");
552-
}
553-
f.close();
554-
555-
if ((max_id + 1) != num_cpus) {
556-
fprintf(stderr,
557-
"CPU ID assignments in /proc/cpuinfo seem messed up."
558-
" This is usually caused by a bad BIOS.\n");
559-
}
560-
return num_cpus;
561514
#endif
562515
BENCHMARK_UNREACHABLE();
563516
}

0 commit comments

Comments
 (0)