Reputation: 3548
Is there an API to get the number of CPUs available in Linux? I mean, without using /proc/cpuinfo or any other sys-node file...
I've found this implementation using sched.h:
int GetCPUCount()
{
cpu_set_t cs;
CPU_ZERO(&cs);
sched_getaffinity(0, sizeof(cs), &cs);
int count = 0;
for (int i = 0; i < 64; i++)
{
if (CPU_ISSET(i, &cs))
count++;
else
break;
}
return count;
}
But, isn't there anything more higher level using common libraries?
Upvotes: 80
Views: 95432
Reputation: 1648
On Linux (Ubuntu):
#ifndef _GNU_SOURCE
# define _GNU_SOURCE
#endif
#include <sched.h>
int GetCPUCount()
{
cpu_set_t cs;
sched_getaffinity(0, sizeof(cs), &cs);
return CPU_COUNT_S(sizeof(cs), &cs);
}
(Assuming the current process has the default CPU affinity.)
Upvotes: 2
Reputation: 9827
Personally for recent Intel cpus (not x86 in general, just Intel) I use the EAX=0Bh
cpuid
leaf. See Wikipedia for some details on what info you get about the cores in the current socket aka package. On a multi-socket system, this might be half or a quarter of the system-wide number of physical / logical cores. Intel has a whitepaper on enumerating CPUs with details on what to check in case of multi-socket systems. This code doesn't do that, it just checks one sub-leaf (ECX=1).
int main()
{
unsigned int eax=11,ebx=0,ecx=1,edx=0;
asm volatile("cpuid"
: "=a" (eax),
"=b" (ebx),
"=c" (ecx),
"=d" (edx)
: "0" (eax), "2" (ecx)
: );
printf("Cores: %d\nThreads: %d\nActual thread: %d\n",eax,ebx,edx);
}
Output:
Cores: 4
Threads: 8
Actual thread: 1
Or, more concisely:
#include <stdio.h>
int main()
{
unsigned int ncores=0,nthreads=0,ht=0;
asm volatile("cpuid": "=a" (ncores), "=b" (nthreads) : "a" (0xb), "c" (0x1) : );
ht=(ncores!=nthreads);
printf("Cores: %d\nThreads: %d\nHyperThreading: %s\n",ncores,nthreads,ht?"Yes":"No");
return 0;
}
Output:
Cores: 4
Threads: 8
HyperThreading: Yes
Upvotes: 6
Reputation: 91
None of the answers that involve sysconf(...)
or get_nprocs()
are correct for honouring the number of processors restricted to a task by cpu affinity.
You need something like this to get the number of processors available to a task:
#define _GNU_SOURCE
#include <sched.h>
#include <stdio.h>
int nprocs()
{
cpu_set_t cs;
CPU_ZERO(&cs);
sched_getaffinity(0, sizeof(cs), &cs);
return CPU_COUNT(&cs);
}
int main()
{
printf("procs=%d\n", nprocs());
return 0;
}
Upvotes: 9
Reputation: 692
#include <stdio.h>
#include <sys/sysinfo.h>
int main(int argc, char *argv[])
{
printf("This system has %d processors configured and "
"%d processors available.\n",
get_nprocs_conf(), get_nprocs());
return 0;
}
https://linux.die.net/man/3/get_nprocs
Upvotes: 57
Reputation: 37930
#include <unistd.h>
long number_of_processors = sysconf(_SC_NPROCESSORS_ONLN);
Upvotes: 102
Reputation: 12658
Another method scanning cpu* directories under sys file system:
#include<stdio.h>
#include <dirent.h>
#include <errno.h>
#define LINUX_SYS_CPU_DIRECTORY "/sys/devices/system/cpu"
int main() {
int cpu_count = 0;
DIR *sys_cpu_dir = opendir(LINUX_SYS_CPU_DIRECTORY);
if (sys_cpu_dir == NULL) {
int err = errno;
printf("Cannot open %s directory, error (%d).\n", LINUX_SYS_CPU_DIRECTORY, strerror(err));
return -1;
}
const struct dirent *cpu_dir;
while((cpu_dir = readdir(sys_cpu_dir)) != NULL) {
if (fnmatch("cpu[0-9]*", cpu_dir->d_name, 0) != 0)
{
/* Skip the file which does not represent a CPU */
continue;
}
cpu_count++;
}
printf("CPU count: %d\n", cpu_count);
return 0;
}
Upvotes: 1
Reputation: 4585
This code (drawn from here) should work on both windows and *NIX platforms.
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#else
#include <unistd.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
int main() {
long nprocs = -1;
long nprocs_max = -1;
#ifdef _WIN32
#ifndef _SC_NPROCESSORS_ONLN
SYSTEM_INFO info;
GetSystemInfo(&info);
#define sysconf(a) info.dwNumberOfProcessors
#define _SC_NPROCESSORS_ONLN
#endif
#endif
#ifdef _SC_NPROCESSORS_ONLN
nprocs = sysconf(_SC_NPROCESSORS_ONLN);
if (nprocs < 1)
{
fprintf(stderr, "Could not determine number of CPUs online:\n%s\n",
strerror (errno));
exit (EXIT_FAILURE);
}
nprocs_max = sysconf(_SC_NPROCESSORS_CONF);
if (nprocs_max < 1)
{
fprintf(stderr, "Could not determine number of CPUs configured:\n%s\n",
strerror (errno));
exit (EXIT_FAILURE);
}
printf ("%ld of %ld processors online\n",nprocs, nprocs_max);
exit (EXIT_SUCCESS);
#else
fprintf(stderr, "Could not determine number of CPUs");
exit (EXIT_FAILURE);
#endif
}
Upvotes: 22
Reputation: 436
sched_affinity()
version you mention in the beginning is still better than /proc/cpuinfo
and/or _SC_NPROCESSORS_ONLN
since it only counts CPUs available for a given process (some may be disabled by sched_setaffinity()
invoked by an outside process). The only change would be using CPU_COUNT()
instead of doing CPU_ISSET
in a loop.
Upvotes: 13
Reputation: 215259
Using /proc/cpuinfo
is the cleanest and most portable solution. In case the open fails, you could simply assume 1 cpu or 2 cpus. Code that depends on knowing the number of cpus for a purpose other than micro-optimizing (e.g. choosing the ideal number of threads to run) is almost surely doing something dumb.
The _SC_NPROCESSORS_ONLN
solution depends on a non-standard (glibc-specific) sysconf
extension, which is a much bigger dependency than /proc
(all Linux systems have /proc
, but some have non-glibc libcs or older versions of glibc that lack _SC_NPROCESSORS_ONLN
).
Upvotes: 12