Platform-Independent Determination of Machine's Core Count
Determining the number of cores on a machine can be essential for optimizing software performance. However, finding a platform-independent solution for this task can be challenging.
C 11 Solution
Fortunately, C 11 has introduced a platform-agnostic method for identifying core count:
#include <thread> const auto processor_count = std::thread::hardware_concurrency();
This method returns the logical number of cores, as reported by the underlying hardware and operating system.
Pre-C 11 Solutions
For C versions prior to C 11, there is no portable way to determine core count. Instead, platform-specific approaches must be used:
Windows
SYSTEM_INFO sysinfo; GetSystemInfo(&sysinfo); int numCPU = sysinfo.dwNumberOfProcessors;
Unix-like Systems
int numCPU = sysconf(_SC_NPROCESSORS_ONLN);
macOS (Prior to 10.5)
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; /* get the number of CPUs from the system */ sysctl(mib, 2, &numCPU, &len, NULL, 0);
Objective-C (macOS 10.5 or Later)
NSUInteger a = [[NSProcessInfo processInfo] processorCount];
The above is the detailed content of How Can I Portably Determine a Machine's Core Count in C ?. For more information, please follow other related articles on the PHP Chinese website!