Get number of CPU’s available

If you need to know how many CPU’s are available this code will help you:

 

 

#include <stdio.h>
#include <sys/param.h>
#include <sys/sysctl.h>

int bu_avail_cpus() {
int mib[2];
size_t len;
int maxproc = 1;

mib[0] = CTL_HW;
mib[1] = HW_NCPU;
len = sizeof(maxproc);
if (sysctl(mib, 2, &maxproc, &len, NULL, NULL == -1)) {
perror("could not determine number of cpus available");
}

return maxproc;