@@ -508,6 +508,55 @@ int GetNumCPUsImpl() {
508508 hardware_threads.max_hthreads = 1 ;
509509 }
510510 return hardware_threads.max_hthreads ;
511+ #else
512+ // Fallback for platforms (such as WASM) that aren't covered above.
513+ int num_cpus = 0 ;
514+ int max_id = -1 ;
515+ std::ifstream f (" /proc/cpuinfo" );
516+ if (!f.is_open ()) {
517+ std::cerr << " Failed to open /proc/cpuinfo\n " ;
518+ return -1 ;
519+ }
520+ #if defined(__alpha__)
521+ const std::string Key = " cpus detected" ;
522+ #else
523+ const std::string Key = " processor" ;
524+ #endif
525+ std::string ln;
526+ while (std::getline (f, ln)) {
527+ if (ln.empty ()) continue ;
528+ std::size_t split_idx = ln.find (' :' );
529+ std::string value;
530+ #if defined(__s390__)
531+ // s390 has another format in /proc/cpuinfo
532+ // it needs to be parsed differently
533+ if (split_idx != std::string::npos)
534+ value = ln.substr (Key.size () + 1 , split_idx - Key.size () - 1 );
535+ #else
536+ if (split_idx != std::string::npos) value = ln.substr (split_idx + 1 );
537+ #endif
538+ if (ln.size () >= Key.size () && ln.compare (0 , Key.size (), Key) == 0 ) {
539+ num_cpus++;
540+ if (!value.empty ()) {
541+ const int cur_id = benchmark::stoi (value);
542+ max_id = std::max (cur_id, max_id);
543+ }
544+ }
545+ }
546+ if (f.bad ()) {
547+ PrintErrorAndDie (" Failure reading /proc/cpuinfo" );
548+ }
549+ if (!f.eof ()) {
550+ PrintErrorAndDie (" Failed to read to end of /proc/cpuinfo" );
551+ }
552+ f.close ();
553+
554+ if ((max_id + 1 ) != num_cpus) {
555+ fprintf (stderr,
556+ " CPU ID assignments in /proc/cpuinfo seem messed up."
557+ " This is usually caused by a bad BIOS.\n " );
558+ }
559+ return num_cpus;
511560#endif
512561 BENCHMARK_UNREACHABLE ();
513562}
@@ -516,7 +565,7 @@ int GetNumCPUs() {
516565 int num_cpus = GetNumCPUsImpl ();
517566 if (num_cpus < 1 ) {
518567 std::cerr << " Unable to extract number of CPUs.\n " ;
519- /* There is at least one CPU which we run on. */
568+ // There must be at least one CPU on which we're running.
520569 num_cpus = 1 ;
521570 }
522571 return num_cpus;
0 commit comments