C++,在windows中使用PdhAddCounter来实时获取cpu使用率和io使用情况
时间: 2024-11-22 15:36:40 浏览: 19
在Windows上,C++可以利用Performance Data Helper (Pdh) API来实时获取CPU使用率和I/O使用情况。以下是一个简化的示例,展示如何添加和读取这两个性能指标:
首先,你需要包含必要的头文件,并初始化Pdh库:
```cpp
#include <pdh.h>
#include <windows.h>
#include <iostream>
```
然后,创建一个查询对象并添加CPU和磁盘I/O的计数器:
```cpp
PDH_HQUERY hQuery;
if (PdhOpenQuery(NULL, PDH_QUERY_PROCESSOR, &hQuery) != ERROR_SUCCESS) {
// 处理打开查询失败
}
LPCOUNTER_PATH cpuPath = "\\Processor(_Total)% Processor Time";
PDH_HCOUNTER cpuCounter;
if (PdhAddCounter(hQuery, cpuPath, NULL, &cpuCounter) != ERROR_SUCCESS) {
// 处理添加CPU计数器失败
}
LPCOUNTER_PATH diskIOPath = "\\System\\Disk Writes/sec"; // 或者 Disk Reads/sec
PDH_HCOUNTER diskIOCounter;
if (PdhAddCounter(hQuery, diskIOPath, NULL, &diskIOCounter) != ERROR_SUCCESS) {
// 处理添加磁盘I/O计数器失败
}
```
接下来,你可以设置定时器来定期收集数据:
```cpp
// 每隔5秒收集一次数据
const DWORD interval = 5000; // in milliseconds
PDH_FMT_COUNTERVALUE values[2] = { {0}, {0} };
while (true) {
if (PdhCollectQueryData(hQuery, values, 2) != ERROR_SUCCESS) {
// 处理收集数据失败
}
float cpuUsage = static_cast<float>(values[0].u_DOUBLE);
uint64_t ioUsage = static_cast<uint64_t>(values[1].ull.QuadPart); // 注意转换为整数
std::cout << "CPU Usage: " << cpuUsage * 100 << "%" << ", Disk I/O: " << ioUsage << " operations\n";
Sleep(interval);
}
```
记得在程序结束时关闭查询和清理内存:
```cpp
PdhCloseQuery(hQuery);
PdhUtilFreeMemory(values[0].pvBuffer);
PdhUtilFreeMemory(values[1].pvBuffer);
```
阅读全文