Home > Backend Development > C++ > How Can I Programmatically Determine the Number of Cores on a Machine?

How Can I Programmatically Determine the Number of Cores on a Machine?

DDD
Release: 2024-12-13 09:23:11
Original
176 people have browsed it

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

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

Linux, Solaris, AIX, Mac OS X >=10.4

int numCPU = sysconf(_SC_NPROCESSORS_ONLN);
Copy after login

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);
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 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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template