Home >Backend Development >C++ >How Can I Programmatically Determine the Number of Cores on a Machine?
Determining the Number of Cores on a Machine Programmatically
In various computing scenarios, understanding the number of cores available on a machine is crucial. C/C does not offer a platform-independent solution for this task. However, there are platform-specific approaches that can provide this information.
C 11 (Platform-Independent)
C 11 introduces the std::thread::hardware_concurrency() function, which provides a portable method to obtain the number of cores.
#include <thread> const auto processor_count = std::thread::hardware_concurrency();
Pre-C 11 (Platform-Specific)
In C prior to C 11, specific methods must be used depending on the platform:
Win32
SYSTEM_INFO sysinfo; GetSystemInfo(&sysinfo); int numCPU = sysinfo.dwNumberOfProcessors;
Linux, Solaris, AIX, Mac OS X >=10.4
int numCPU = sysconf(_SC_NPROCESSORS_ONLN);
FreeBSD, MacOS X, NetBSD, OpenBSD
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);
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];
By utilizing these platform-specific methods or the C 11 platform-independent approach, you can programmatically determine the number of cores available on a machine, enabling you to optimize resource utilization and achieve better performance in your applications.
The above is the detailed content of How Can I Programmatically Determine the Number of Cores on a Machine?. For more information, please follow other related articles on the PHP Chinese website!