c语言查看cpu温度代码_C语言获取CPU核心温度

获取Intel CPU 信息和温度

CPU信息可以通过cpuid指令获取,在用户空间可以通过内嵌汇编代码实现,代码如下:

struct cpuid_res {

uint32_t eax;

uint32_t ebx;

uint32_t ecx;

uint32_t edx;

};

static inline struct cpuid_res cpuid(int op)

{

struct cpuid_res result;

asm volatile(

"mov %%ebx, %%edi;"

"cpuid;"

"mov %%ebx, %%esi;"

"mov %%edi, %%ebx;"

: "=a" (result.eax),

"=S" (result.ebx),

"=c" (result.ecx),

"=d" (result.edx)

: "0" (op)

: "edi");

return result;

}

获取CPU厂家名称

以eax=0 执行 cpuid,eax为0表示读取vendor id,一共12字节,依次在ebx、edx、ecx

result = cpuid(0);

vendor_name[0] = (result.ebx >> 0) & 0xff;

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
获取CPU温度需要使用操作系统提供的API接口,而不是使用纯C语言编写的代码。下面给出两种常用的获取CPU温度的方法。 1. 使用Linux下的lm-sensors工具获取CPU温度 lm-sensors是Linux下的一个硬件监控工具,可以用来获取CPU温度等硬件信息。使用C语言调用lm-sensors的API接口可以获取CPU温度。下面是一个示例代码片段: ``` #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_LINE_LEN 1024 int main() { char cmd[MAX_LINE_LEN] = "sensors | grep 'Core 0' | awk '{print $3}'"; char buf[MAX_LINE_LEN]; FILE *fp; fp = popen(cmd, "r"); fgets(buf, MAX_LINE_LEN, fp); pclose(fp); int temp = atoi(buf); printf("CPU temperature: %d°C\n", temp); return 0; } ``` 这段代码通过执行命令`sensors | grep 'Core 0' | awk '{print $3}'`获取CPU Core 0的温度,然后将结果转换为整数输出。 2. 使用Windows下的WMI获取CPU温度 在Windows系统下,可以使用WMI(Windows Management Instrumentation)获取CPU温度。WMI是Windows提供的一组API接口,可以用来获取系统信息。下面是一个示例代码片段: ``` #include <stdio.h> #include <windows.h> #include <wbemidl.h> #pragma comment(lib, "wbemuuid.lib") int main() { HRESULT hr; IWbemLocator *pLoc = NULL; IWbemServices *pSvc = NULL; IEnumWbemClassObject *pEnum = NULL; BSTR bstrQuery = NULL; BSTR bstrWQL = NULL; ULONG uReturn = 0; VARIANT vtProp; CIMTYPE cimtype; CoInitialize(NULL); hr = CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID *)&pLoc); hr = pLoc->ConnectServer(_bstr_t(L"ROOT\\WMI"), NULL, NULL, 0, NULL, 0, 0, &pSvc); bstrWQL = SysAllocString(L"WQL"); bstrQuery = SysAllocString(L"SELECT * FROM MSAcpi_ThermalZoneTemperature"); hr = pSvc->ExecQuery(bstrWQL, bstrQuery, WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnum); hr = pEnum->Next(WBEM_INFINITE, 1, &vtProp, &uReturn); if (uReturn) { printf("CPU temperature: %d°C\n", (vtProp.lVal - 2732) / 10); VariantClear(&vtProp); } pEnum->Release(); pSvc->Release(); pLoc->Release(); CoUninitialize(); return 0; } ``` 这段代码使用WMI接口查询MSAcpi_ThermalZoneTemperature类的数据,然后将结果转换为整数输出。需要注意的是,由于WMI获取温度单位为0.1K,需要进行一定的计算才能转换为摄氏度。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值