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

CLinuxMultithreadingCpuProcessor

C Problem Overview


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?

C Solutions


Solution 1 - C

#include <unistd.h>
long number_of_processors = sysconf(_SC_NPROCESSORS_ONLN);

Solution 2 - C

#include <stdio.h>
#include <sys/sysinfo.h>

int main(int argc, char *argv[])
{
    printf("This system has %d processors configured and "
        "%d processors available.\n",
        get_nprocs_conf(), get_nprocs());
    return 0;
}

https://linux.die.net/man/3/get_nprocs

Solution 3 - C

This code (drawn from here) should work on both windows and *NIX platforms.

#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#else
#include <unistd.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>


int main() {
  long nprocs = -1;
  long nprocs_max = -1;
#ifdef _WIN32
#ifndef _SC_NPROCESSORS_ONLN
SYSTEM_INFO info;
GetSystemInfo(&info);
#define sysconf(a) info.dwNumberOfProcessors
#define _SC_NPROCESSORS_ONLN
#endif
#endif
#ifdef _SC_NPROCESSORS_ONLN
  nprocs = sysconf(_SC_NPROCESSORS_ONLN);
  if (nprocs < 1)
  {
    fprintf(stderr, "Could not determine number of CPUs online:\n%s\n", 
strerror (errno));
    exit (EXIT_FAILURE);
  }
  nprocs_max = sysconf(_SC_NPROCESSORS_CONF);
  if (nprocs_max < 1)
  {
    fprintf(stderr, "Could not determine number of CPUs configured:\n%s\n", 
strerror (errno));
    exit (EXIT_FAILURE);
  }
  printf ("%ld of %ld processors online\n",nprocs, nprocs_max);
  exit (EXIT_SUCCESS);
#else
  fprintf(stderr, "Could not determine number of CPUs");
  exit (EXIT_FAILURE);
#endif
}

Solution 4 - C

Using /proc/cpuinfo is the cleanest and most portable solution. In case the open fails, you could simply assume 1 cpu or 2 cpus. Code that depends on knowing the number of cpus for a purpose other than micro-optimizing (e.g. choosing the ideal number of threads to run) is almost surely doing something dumb.

The _SC_NPROCESSORS_ONLN solution depends on a non-standard (glibc-specific) sysconf extension, which is a much bigger dependency than /proc (all Linux systems have /proc, but some have non-glibc libcs or older versions of glibc that lack _SC_NPROCESSORS_ONLN).

Solution 5 - C

sched_affinity() version you mention in the beginning is still better than /proc/cpuinfo and/or _SC_NPROCESSORS_ONLN since it only counts CPUs available for a given process (some may be disabled by sched_setaffinity() invoked by an outside process). The only change would be using CPU_COUNT() instead of doing CPU_ISSET in a loop.

Solution 6 - C

Personally for recent intel cpus I use this:

int main()
{
unsigned int eax=11,ebx=0,ecx=1,edx=0;

asm volatile("cpuid"
	    : "=a" (eax),
	      "=b" (ebx),
	      "=c" (ecx),
	      "=d" (edx)
	    : "0" (eax), "2" (ecx)
	    : );
	    	
printf("Cores: %d\nThreads: %d\nActual thread: %d\n",eax,ebx,edx);
}

Output:

Cores: 4
Threads: 8
Actual thread: 1

Or, more concisely:

#include <stdio.h>

int main()
{
unsigned int ncores=0,nthreads=0,ht=0;

asm volatile("cpuid": "=a" (ncores), "=b" (nthreads) : "a" (0xb), "c" (0x1) : );

ht=(ncores!=nthreads);

printf("Cores: %d\nThreads: %d\nHyperThreading: %s\n",ncores,nthreads,ht?"Yes":"No");

return 0;
}

Output:

Cores: 4
Threads: 8
HyperThreading: Yes

Solution 7 - C

None of the answers that involve sysconf(...) or get_nprocs() are correct for honouring the number of processors restricted to a task by cpu affinity.

You need something like this to get the number of processors available to a task:

#define _GNU_SOURCE
#include <sched.h>
#include <stdio.h>

int nprocs()
{
  cpu_set_t cs;
  CPU_ZERO(&cs);
  sched_getaffinity(0, sizeof(cs), &cs);
  return CPU_COUNT(&cs);
}

int main()
{
  printf("procs=%d\n", nprocs());
  return 0;
}

Solution 8 - C

Another method scanning cpu* directories under sys file system:

#include<stdio.h>
#include <dirent.h>
#include <errno.h>
#define LINUX_SYS_CPU_DIRECTORY "/sys/devices/system/cpu"

int main() {
   int cpu_count = 0;
   DIR *sys_cpu_dir = opendir(LINUX_SYS_CPU_DIRECTORY);
   if (sys_cpu_dir == NULL) {
       int err = errno;
       printf("Cannot open %s directory, error (%d).\n", LINUX_SYS_CPU_DIRECTORY, strerror(err));
       return -1;
   }
   const struct dirent *cpu_dir;
   while((cpu_dir = readdir(sys_cpu_dir)) != NULL) {
       if (fnmatch("cpu[0-9]*", cpu_dir->d_name, 0) != 0)
       {
          /* Skip the file which does not represent a CPU */
          continue;
       }
       cpu_count++;
   }
   printf("CPU count: %d\n", cpu_count);
   return 0;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTrevi&#241;oView Question on Stackoverflow
Solution 1 - CchrisaycockView Answer on Stackoverflow
Solution 2 - CВладимир НиколайчукView Answer on Stackoverflow
Solution 3 - CVikram.exeView Answer on Stackoverflow
Solution 4 - CR.. GitHub STOP HELPING ICEView Answer on Stackoverflow
Solution 5 - CRCLView Answer on Stackoverflow
Solution 6 - CZibriView Answer on Stackoverflow
Solution 7 - CDamien ZammitView Answer on Stackoverflow
Solution 8 - CSunil BojanapallyView Answer on Stackoverflow