Skip to content

Commit c24774d

Browse files
authored
Get number of CPUs with sysconf() on Linux (google#1901)
* Get number of CPUs with sysconf() on Linux Avoid parsing the /proc/cpuinfo just to get number of CPUs. Instead use the portable function provided by glibc. * Update sysinfo.cc
1 parent 39be87d commit c24774d

File tree

1 file changed

+3
-51
lines changed

1 file changed

+3
-51
lines changed

src/sysinfo.cc

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

0 commit comments

Comments
 (0)