window下获取CPU温度 C++代码
时间: 2024-04-09 12:33:51 浏览: 124
获取CPU温度的脚本
4星 · 用户满意度95%
你可以使用第三方库来获取Windows下的CPU温度,以下是一个示例的C++代码:
```cpp
#include <iostream>
#include <Windows.h>
#include <pdh.h>
#pragma comment(lib, "pdh.lib")
float GetCpuTemperature()
{
HQUERY hQuery;
PDH_STATUS pdhStatus;
HCOUNTER hCounter;
DWORD dwType;
PPDH_FMT_COUNTERVALUE pValue;
pdhStatus = PdhOpenQuery(NULL, NULL, &hQuery);
if (pdhStatus != ERROR_SUCCESS)
{
std::cout << "PdhOpenQuery failed with status: " << pdhStatus << std::endl;
return -1.0f;
}
pdhStatus = PdhAddCounter(hQuery, L"\\Processor(_Total)\\% Processor Time", NULL, &hCounter);
if (pdhStatus != ERROR_SUCCESS)
{
std::cout << "PdhAddCounter failed with status: " << pdhStatus << std::endl;
PdhCloseQuery(hQuery);
return -1.0f;
}
pdhStatus = PdhCollectQueryData(hQuery);
if (pdhStatus != ERROR_SUCCESS)
{
std::cout << "PdhCollectQueryData failed with status: " << pdhStatus << std::endl;
PdhCloseQuery(hQuery);
return -1.0f;
}
Sleep(1000); // 等待一秒钟
pdhStatus = PdhCollectQueryData(hQuery);
if (pdhStatus != ERROR_SUCCESS)
{
std::cout << "PdhCollectQueryData failed with status: " << pdhStatus << std::endl;
PdhCloseQuery(hQuery);
return -1.0f;
}
pdhStatus = PdhGetFormattedCounterValue(hCounter, PDH_FMT_DOUBLE, &dwType, pValue);
if (pdhStatus != ERROR_SUCCESS)
{
std::cout << "PdhGetFormattedCounterValue failed with status: " << pdhStatus << std::endl;
PdhCloseQuery(hQuery);
return -1.0f;
}
PdhCloseQuery(hQuery);
// 假设CPU温度与CPU使用率成正比,可以将CPU使用率作为温度值返回
return static_cast<float>(pValue->doubleValue);
}
int main()
{
float temperature = GetCpuTemperature();
if (temperature != -1.0f)
{
std::cout << "CPU Temperature: " << temperature << " %" << std::endl;
}
return 0;
}
```
请注意,该代码使用了 Windows PDH (Performance Data Helper) API 来获取CPU使用率,并假设CPU温度与使用率成正比。这只是一个简单的示例,实际情况可能因硬件和操作系统的不同而有所区别。你可能需要根据具体的硬件和操作系统来选择适合的方法来获取CPU温度。
阅读全文