优先使用std::thread::hardware_concurrency()获取CPU核心数,跨平台且简洁;若返回0则回退到系统API:Windows调用GetSystemInfo,Linux读取/proc/cpuinfo统计processor字段。

在C++中跨平台获取CPU核心数,可以通过调用系统提供的API或标准库函数来实现。Windows和Linux有不同的接口,但我们可以封装成统一的接口,方便在不同系统上调用。
使用标准库 std::thread::hardware_concurrency()
最简单且跨平台的方法是使用C++11引入的 std::thread::hardware_concurrency()。这个函数会返回系统支持的并发线程数量,通常等于逻辑核心数。示例代码:
#include <iostream>
#include <thread>
int main() {
unsigned int num_cores = std::thread::hardware_concurrency();
if (num_cores == 0) {
std::cout <font color="#2F4F4F">优点:无需平台判断,一行代码搞定。缺点:某些系统可能返回0(表示信息不可用)。</font><h3>Windows平台:使用GetSystemInfo</h3>
<font color="#2F4F4F">在Windows上,可以调用Win32 API中的 <strong>GetSystemInfo</strong> 函数来获取<a style="color:#f60; text-decoration:underline;" title="处理器" href="https://m.php.cn/zt/16030.html" target="_blank">处理器</a>核心信息。</font><p>示例代码:</p>
<pre class="brush:php;toolbar:false;">#include <iostream>
#ifdef _WIN32
#include <windows.h>
int get_cpu_cores_windows() {
SYSTEM_INFO sysinfo;
GetSystemInfo(&sysinfo);
return sysinfo.dwNumberOfProcessors;
}
#endif
int main() {
#ifdef _WIN32
std::cout <h3>Linux平台:读取 /proc/cpuinfo</h3>
<font color="#2F4F4F">Linux系统将CPU信息保存在 <strong>/proc/cpuinfo</strong> 文件中,可以通过读取该文件并统计<strong>processor</strong>字段的数量来获得逻辑核心数。</font><p>示例代码:</p>
<pre class="brush:php;toolbar:false;">#include <iostream>
#include <fstream>
#include <string>
#ifdef __linux__
int get_cpu_cores_linux() {
std::ifstream file("/proc/cpuinfo");
std::string line;
int count = 0;
if (file.is_open()) {
while (getline(file, line)) {
if (line.rfind("processor", 0) == 0) {
count++;
}
}
file.close();
}
return count;
}
#endif
int main() {
#ifdef __linux__
std::cout <h3>跨平台封装建议</h3>
<font color="#2F4F4F">为了兼容多个平台,可以将上述方法封装成一个函数,优先使用标准库,失败时再回退到平台特定方法。</font><p>统一接口示例:</p>
<pre class="brush:php;toolbar:false;">#include <iostream>
#include <thread>
int get_cpu_cores() {
// 尝试使用标准库
unsigned int hw_cores = std::thread::hardware_concurrency();
if (hw_cores != 0) {
return hw_cores;
}
#ifdef _WIN32
SYSTEM_INFO sysinfo;
GetSystemInfo(&sysinfo);
return sysinfo.dwNumberOfProcessors;
#elif __linux__
std::ifstream file("/proc/cpuinfo");
std::string line;
int count = 0;
while (getline(file, line)) {
if (line.rfind("processor", 0) == 0) {
count++;
}
}
return count;
#else
return 1; // 未知平台默认返回1
#endif
}
int main() {
std::cout <p>基本上就这些。推荐优先使用 <strong>std::thread::hardware_concurrency()</strong>,简洁可靠。只有在需要更高精度或处理特殊场景时,才考虑调用系统API或解析系统文件。</p></thread></iostream>
C++免费学习笔记(深入):立即使用
在学习笔记中,你将探索 C++ 的入门与实战技巧!











