Linux下用C++读取CPU核心温度的核心数匹配问题
解决CPU核心温度与逻辑核心数不匹配的问题
问题根源
你的CPU是6物理核心+12逻辑核心(开启了超线程):
/proc/stat、system monitor、btop显示的是逻辑核心数(12个),这是操作系统层面的调度单元sensors和coretemp驱动输出的是物理核心的温度(6个),因为同物理核心下的两个逻辑核心共享同一个温度传感器,无需重复上报
验证方式
运行lscpu命令,重点看这几个字段:
CPU(s): 12→ 逻辑核心总数Core(s) per socket: 6→ 单插槽物理核心数Thread(s) per core: 2→ 每个物理核心对应2个逻辑核心(超线程已开启)
获取12个逻辑核心温度的实现方案
1. 关联逻辑核心与物理核心
读取/proc/cpuinfo文件,每个逻辑核心的条目里有core id字段,用来标记所属的物理核心。示例片段:
processor : 0 core id : 0 ... processor : 1 core id : 0 ...
这里逻辑核心0和1属于同一个物理核心(core id为0),共享同一温度传感器。
2. 读取物理核心温度
从/sys/devices/platform/coretemp.0/hwmon/hwmon2/路径下读取温度文件,文件命名为tempX_input(X从1开始,对应每个物理核心),文件内容是毫摄氏度单位的温度值。
3. 映射温度到逻辑核心
将同一个物理核心对应的所有逻辑核心,统一赋值该物理核心的温度即可。
C++实现示例代码
#include <iostream> #include <fstream> #include <string> #include <map> #include <vector> // 建立逻辑核心到物理核心的映射 std::map<int, int> build_core_mapping() { std::map<int, int> core_map; std::ifstream cpuinfo("/proc/cpuinfo"); std::string line; int logical_core = -1; int physical_core_id = -1; while (std::getline(cpuinfo, line)) { if (line.find("processor") != std::string::npos) { logical_core = std::stoi(line.substr(line.find(":") + 1)); } else if (line.find("core id") != std::string::npos) { physical_core_id = std::stoi(line.substr(line.find(":") + 1)); core_map[logical_core] = physical_core_id; } } return core_map; } // 读取所有物理核心的温度(转换为摄氏度) std::vector<int> get_physical_core_temps(const std::string& hwmon_dir) { std::vector<int> temps; int idx = 1; while (true) { std::string temp_path = hwmon_dir + "/temp" + std::to_string(idx) + "_input"; std::ifstream temp_file(temp_path); if (!temp_file.is_open()) break; int raw_temp; temp_file >> raw_temp; temps.push_back(raw_temp / 1000); // 毫摄氏度转摄氏度 idx++; temp_file.close(); } return temps; } int main() { auto core_mapping = build_core_mapping(); auto physical_temps = get_physical_core_temps("/sys/devices/platform/coretemp.0/hwmon/hwmon2"); std::cout << "各逻辑核心温度:" << std::endl; for (const auto& pair : core_mapping) { int logical_core = pair.first; int physical_idx = pair.second; // 注意:tempX_input的X从1开始,对应core id从0开始,所以索引直接对应 int temp = physical_temps[physical_idx]; std::cout << "逻辑核心 " << logical_core << ": " << temp << "°C" << std::endl; } return 0; }
注意事项
- 不同机器的
hwmon编号(比如hwmon2)可能不同,可通过/sys/class/hwmon/hwmon*/name文件确认,找名称为coretemp的目录 - 部分CPU的
core id可能不是连续编号,需以/proc/cpuinfo的实际输出为准 - 若需要实时更新温度,可定时重复执行读取逻辑
内容的提问来源于stack exchange,提问作者user20295136
相关产品推荐
相关产品推荐

