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
Release: 2024-12-14 18:10:11
Original
430 people have browsed it

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();
Copy after login

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;
Copy after login

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

int numCPU = sysconf(_SC_NPROCESSORS_ONLN);
Copy after login

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;
}
Copy after login

HPUX

int numCPU = mpctl(MPC_GETNUMSPUS, NULL, NULL);
Copy after login

IRIX

int numCPU = sysconf(_SC_NPROC_ONLN);
Copy after login

Objective-C (Mac OS X >= 10.5 or iOS)

NSUInteger a = [[NSProcessInfo processInfo] processorCount];
NSUInteger b = [[NSProcessInfo processInfo] activeProcessorCount];
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template