From time to time you may need to know at runtime how many processors (or more accurately processor cores) are available to your program. For example, you might want to determine how many threads to use with multi-threaded FFTW.
Darel Finley succinctly shows how to do this programmatically on Mac OS X. The same code unchanged compiles on FreeBSD, and I’ve added code for Linux, and wrapped it in CPP conditionals to detect which code to use at compile time. If compiled on something other than Mac OS X, FreeBSD or Linux, the value returned defaults to 1. So without further ado, here’s nproc.c:
/* Compile with: gcc -o nproc nproc.c */
#include <stdio.h>
#include <sys/param.h>
#include <sys/sysctl.h>
int CPUCount()
{
int count;
#if defined(__APPLE__) || defined(__FreeBSD__)
size_t size = sizeof(int);
if (sysctlbyname("hw.ncpu",&count,&size,NULL,0)!=0)
return(1);
else
return(count);
#elif defined(__linux__)
char *fname = "/proc/cpuinfo";
char input[256];
FILE *ptr;
if ((ptr = fopen(fname, "r")) == NULL) return(1);
count = 0;
while (fgets(input, 256, ptr))
if (strncmp("processor", input, 9) == 0)
count++;
fclose(ptr);
return((count>0)?count:1);
#else
return(1);
#endif
}
int main(void)
{
printf("CPU Count: %d\n", CPUCount());
return(0);
}
Posted by Cyber Feen 
