Programmatically find the number of cores on a machine
Is there a way to determine how many cores a machine has from C/C++ in a platform-independent way? If no such thing exists, what about determining it per-platform (Windows/*nix/Mac)?
C++11
#include <thread>
//may return 0 when not able to detect
const auto processor_count = std::thread::hardware_concurrency();
Reference: std::thread::hardware_concurrency
In C++ prior to C++11, there's no portable way. Instead, you'll need to use one or more of the following methods (guarded by appropriate #ifdef
lines):
-
Win32
SYSTEM_INFO sysinfo; GetSystemInfo(&sysinfo); int numCPU = sysinfo.dwNumberOfProcessors;
-
Linux, Solaris, AIX and Mac OS X >=10.4 (i.e. Tiger onwards)
int numCPU = sysconf(_SC_NPROCESSORS_ONLN);
-
FreeBSD, MacOS X, NetBSD, OpenBSD, etc.
int mib[4]; int numCPU; std::size_t len = sizeof(numCPU); /* set the mib for hw.ncpu */ mib[0] = CTL_HW; mib[1] = HW_AVAILCPU; // alternatively, try HW_NCPU; /* get the number of CPUs from the system */ sysctl(mib, 2, &numCPU, &len, NULL, 0); if (numCPU < 1) { mib[1] = HW_NCPU; sysctl(mib, 2, &numCPU, &len, NULL, 0); if (numCPU < 1) numCPU = 1; }
-
HPUX
int numCPU = mpctl(MPC_GETNUMSPUS, NULL, NULL);
-
IRIX
int numCPU = sysconf(_SC_NPROC_ONLN);
-
Objective-C (Mac OS X >=10.5 or iOS)
NSUInteger a = [[NSProcessInfo processInfo] processorCount]; NSUInteger b = [[NSProcessInfo processInfo] activeProcessorCount];
This functionality is part of the C++11 standard.
#include <thread>
unsigned int nthreads = std::thread::hardware_concurrency();
For older compilers, you can use the Boost.Thread library.
#include <boost/thread.hpp>
unsigned int nthreads = boost::thread::hardware_concurrency();
In either case, hardware_concurrency()
returns the number of threads that the hardware is capable of executing concurrently based on the number of CPU cores and hyper-threading units.
OpenMP is supported on many platforms (including Visual Studio 2005) and it offers a
int omp_get_num_procs();
function that returns the number of processors/cores available at the time of call.