Created
January 9, 2022 00:10
-
-
Save vankxr/883882ac52c77949d4dc2ba1e69182d3 to your computer and use it in GitHub Desktop.
C get number of CPU threads
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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