

新闻资讯
技术学院优先使用std::thread::hardware_concurrency()获取CPU核心数,跨平台且简洁;若返回0则回退到系统API:Windows调用GetSystemInfo,Linux读取/proc/cpuinfo统计processor字段。
在C++中跨平台获取CPU核心数,可以通过调用系统提供的API或标准库函数来实现。Windows和Linux有不同的接口,但我们可以封装成统一的接口,方便在不同系统上调用。
示例代码:
#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; }
示例代码:
#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; }
示例代码:
#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_co res != 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或解析系统文件。