Home > Backend Development > C++ > How Can I Portably Determine a Machine's Core Count in C ?

How Can I Portably Determine a Machine's Core Count in C ?

DDD
Release: 2024-12-29 02:55:10
Original
141 people have browsed it

How Can I Portably Determine a Machine's Core Count in C  ?

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

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

Unix-like Systems

int numCPU = sysconf(_SC_NPROCESSORS_ONLN);
Copy after login

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

Objective-C (macOS 10.5 or Later)

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

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!

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