How do I retrieve the number of processors on C / Linux? How do I retrieve the number of processors on C / Linux? c c

How do I retrieve the number of processors on C / Linux?


As others have mentioned in comments, this answer is useful:

numCPU = sysconf( _SC_NPROCESSORS_ONLN );

Leaving as a solution for folks that might skip over comments...


Why not use sys/sysinfo.h?

#include <sys/sysinfo.h>#include <stdio.h>void main () {   printf ("You have %d processors.\n", get_nprocs ());}

Way more information can be found on the man page

$ man 3 get_nprocs


machine:/sys/devices/system/cpu$ lscpu0  cpu3  cpu6     kernel_max  perf_counters  sched_mc_power_savingscpu1  cpu4  cpu7     offline     possiblecpu2  cpu5  cpuidle  online      present

If you have a machine with sysfs, take a look in /sys/devices/system/cpu.

Make sure you're asking for what you want -- CPUs, cores, hyperthreads, etc.