Wednesday, December 26, 2012

Detect Number of Processor Cores

$ cat a.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

int main()
{
    long cpus;
    char *envconfig;

    cpus = sysconf(_SC_NPROCESSORS_CONF);
    printf("Processors configured: %d\n", cpus);
    cpus = sysconf(_SC_NPROCESSORS_ONLN);
    printf("Processors online:     %d\n", cpus);
    envconfig = getenv("PARALLEL");
    if (NULL == envconfig) {
        printf("PARALLEL not defined\n");
    } else {
        printf("PARALLEL=%s (%d)\n", envconfig, strlen(envconfig));
    }
    if ((NULL != envconfig) && (0 == strcmp("OFF", envconfig))) {
        printf("PARALLEL=OFF\n");
    } else {
        printf("PARALLEL=ON\n");
    }

    return 0;
}

$ gcc a.c
$ ./a.out
Processors configured: 2
Processors online:     2
PARALLEL= (0)
PARALLEL=ON

$ export PARALLEL=OFF
$ ./a.out
Processors configured: 2
Processors online:     2
PARALLEL=OFF

$ export PARALLEL=ON
$ ./a.out

Processors configured: 2
Processors online:     2
PARALLEL=ON (2)
PARALLEL=ON

$ export PARALLEL=
$ ./a.out
Processors configured: 2
Processors online:     2
PARALLEL= (0)
PARALLEL=ON

No comments: