优先使用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()。这个函数会返回系统支持的并发线程数量,通常等于逻辑核心数。示例代码:
立即学习“C++免费学习笔记(深入)”;
#include优点:无需平台判断,一行代码搞定。缺点:某些系统可能返回0(表示信息不可用)。#include int main() { unsigned int num_cores = std::thread::hardware_concurrency(); if (num_cores == 0) { std::cout << "无法获取核心数\n"; } else { std::cout << "逻辑核心数: " << num_cores << '\n'; } return 0; }
Windows平台:使用GetSystemInfo
在Windows上,可以调用Win32 API中的 GetSystemInfo 函数来获取处理器核心信息。示例代码:
立即学习“C++免费学习笔记(深入)”;
#include#ifdef _WIN32 #include int get_cpu_cores_windows() { SYSTEM_INFO sysinfo; GetSystemInfo(&sysinfo); return sysinfo.dwNumberOfProcessors; } #endif int main() { #ifdef _WIN32 std::cout << "Windows CPU核心数: " << get_cpu_cores_windows() << '\n'; #endif return 0; }
Linux平台:读取 /proc/cpuinfo
Linux系统将CPU信息保存在 /proc/cpuinfo 文件中,可以通过读取该文件并统计processor字段的数量来获得逻辑核心数。示例代码:
立即学习“C++免费学习笔记(深入)”;
#include#include #include #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 << "Linux CPU核心数: " << get_cpu_cores_linux() << '\n'; #endif return 0; }
跨平台封装建议
为了兼容多个平台,可以将上述方法封装成一个函数,优先使用标准库,失败时再回退到平台特定方法。统一接口示例:
#include#include 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 << "检测到CPU核心数: " << get_cpu_cores() << '\n'; return 0; }
基本上就这些。推荐优先使用 std::thread::hardware_concurrency(),简洁可靠。只有在需要更高精度或处理特殊场景时,才考虑调用系统API或解析系统文件。











