Home >Backend Development >C++ >How to Programmatically Determine the Number of CPU Cores in Different Systems?

How to Programmatically Determine the Number of CPU Cores in Different Systems?

Susan Sarandon
Susan SarandonOriginal
2024-12-14 18:10:11430browse

How to Programmatically Determine the Number of CPU Cores in Different Systems?

Determining the Number of Machine Cores Programmatically

In various scenarios, it becomes imperative to ascertain the number of cores a machine possesses. This information aids in optimizing resource allocation and understanding system capabilities. Several methods exist to determine this crucial metric.

C 11 and Onwards

C 11 introduced a portable solution for retrieving the core count:

#include <thread>

// May return 0 if unable to detect.
const auto processor_count = std::thread::hardware_concurrency();

Pre-C 11 and Platform-Specific Approaches

Prior to C 11, platform-specific methods were employed:

Windows

SYSTEM_INFO sysinfo;
GetSystemInfo(&sysinfo);
int numCPU = sysinfo.dwNumberOfProcessors;

Linux, Solaris, AIX, Mac OS X (Tiger onwards)

int numCPU = sysconf(_SC_NPROCESSORS_ONLN);

FreeBSD, macOS, NetBSD, OpenBSD

int mib[4];
int numCPU;
std::size_t len = sizeof(numCPU); 

mib[0] = CTL_HW;
mib[1] = HW_AVAILCPU;

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];

By leveraging these techniques, developers can effortlessly determine the number of cores available on their machines, enabling efficient resource utilization and performance optimization.

The above is the detailed content of How to Programmatically Determine the Number of CPU Cores in Different Systems?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn