How to get the number of CPUs in Linux using C?

Treviño picture Treviño · Jan 3, 2011 · Viewed 65k times · Source

Is there an API to get the number of CPUs available in Linux? I mean, without using /proc/cpuinfo or any other sys-node file...

I've found this implementation using sched.h:

int GetCPUCount()
{
 cpu_set_t cs;
 CPU_ZERO(&cs);
 sched_getaffinity(0, sizeof(cs), &cs);

 int count = 0;
 for (int i = 0; i < 8; i++)
 {
  if (CPU_ISSET(i, &cs))
   count++;
 }
 return count;
}

But, isn't there anything more higher level using common libraries?

Answer

chrisaycock picture chrisaycock · Jan 3, 2011
#include <unistd.h>
long number_of_processors = sysconf(_SC_NPROCESSORS_ONLN);