Skip to content

Instantly share code, notes, and snippets.

@vankxr
Created January 9, 2022 00:10
Show Gist options
  • Save vankxr/883882ac52c77949d4dc2ba1e69182d3 to your computer and use it in GitHub Desktop.
Save vankxr/883882ac52c77949d4dc2ba1e69182d3 to your computer and use it in GitHub Desktop.
C get number of CPU threads
int ncpus(void) {
FILE *cmd = popen("grep '^processor' /proc/cpuinfo | wc -l", "r");
if (cmd == NULL)
return -1;
unsigned nprocs;
size_t n;
char buff[8];
if ((n = fread(buff, 1, sizeof(buff)-1, cmd)) <= 0)
return -1;
buff[n] = '\0';
if (sscanf(buff, "%u", &nprocs) != 1)
return -1;
pclose(cmd);
return nprocs;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment