Detecting the Number of CPU Cores in Various Programming Environments
Introduction
Determining the number of cores on a machine is a crucial aspect for optimizing code performance and resource allocation. While there is no universal solution across all platforms, there are platform-specific methods available.
C 11 and Later
C 11 introduces the std::thread::hardware_concurrency() function, providing a standardized way to retrieve the number of hardware threads. This method is recommended for cross-platform compatibility.
#include <thread> const auto processor_count = std::thread::hardware_concurrency();
Pre-C 11 Alternative
Prior to C 11, platform-specific methods are required.
Win32:
SYSTEM_INFO sysinfo; GetSystemInfo(&sysinfo); int numCPU = sysinfo.dwNumberOfProcessors;
Linux, Solaris, AIX, Mac OS X:
int numCPU = sysconf(_SC_NPROCESSORS_ONLN);
FreeBSD, MacOS X, NetBSD:
int numCPU; ... sysctl(mib, 2, &numCPU, &len, NULL, 0);
Objective-C for Mac OS X and iOS
Objective-C offers a straightforward approach:
NSUInteger processorCount = [[NSProcessInfo processInfo] processorCount];
The above is the detailed content of How Can I Detect the Number of CPU Cores in Different Programming Languages and Environments?. For more information, please follow other related articles on the PHP Chinese website!