Skip to content

Instantly share code, notes, and snippets.

@amitsaha
Created August 28, 2014 05:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amitsaha/47cc0069bbc89a718700 to your computer and use it in GitHub Desktop.
Save amitsaha/47cc0069bbc89a718700 to your computer and use it in GitHub Desktop.
# define _GNU_SOURCE
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
# include <unistd.h>
# include <sched.h>
# define SYS_IND_CPU_PATH "/sys/devices/system/cpu/cpu"
# define KERNEL_MAX_CPU_PATH "/sys/devices/system/cpu/kernel_max"
int get_num_digits(int num) {
int dig = 0;
while(num > 0) {
dig++;
num = num / 10;
}
return dig;
}
int main(int argc, char **argv){
cpu_set_t *thread_siblings, *core_siblings, *book_siblings, *set;
int nbooks, nsockets, ncores, nthreads;
FILE *fp;
int maxcpus, ncpus=0, loopvar;
char *cpu_string;
/* Find the maximum number of CPUs allowed by the kernel*/
fp = fopen(KERNEL_MAX_CPU_PATH, "r");
fscanf(fp, "%d", &maxcpus);
printf("Max number of CPUs allowed by Kernel %d\n", maxcpus);
fclose(fp);
/* Find the number of online CPUs*/
for(loopvar = 0; loopvar < maxcpus; loopvar++)
{
cpu_string = malloc(strlen(SYS_IND_CPU_PATH) + get_num_digits(loopvar));
sprintf(cpu_string, "%s%d", SYS_IND_CPU_PATH, loopvar);
if (!access(cpu_string, R_OK)) {
ncpus++;
free(cpu_string);
}
else
{
free(cpu_string);
break;
}
}
printf("Online CPUs %d\n", ncpus);
size_t setsize = CPU_ALLOC_SIZE(maxcpus);
/* threads within one core */
nthreads = CPU_COUNT_S(setsize, thread_siblings);
/* cores within one socket */
ncores = CPU_COUNT_S(setsize, core_siblings) / nthreads;
/* number of sockets within one book */
nsockets = ncpus / nthreads / ncores;
/* number of books */
nbooks = ncpus / nthreads / ncores / nsockets;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment