#include <iostream>#include <pdh.h>#pragma comment(lib, "pdh.lib")int main(){ PDH_STATUS status; HQUERY hQuery; HCOUNTER hCounter; PDH_FMT_COUNTERVALUE counterValue; // 打开查询 status = PdhOpenQuery(NULL, 0, &hQuery); if (status != ERROR_SUCCESS) { std::cout << "打开查询失败:" << status << std::endl; return 1; } // 添加计数器 status = PdhAddCounter(hQuery, L"\PhysicalDisk(_Total)\Disk Read Bytes/sec", 0, &hCounter); if (status != ERROR_SUCCESS) { std::cout << "添加计数器失败:" << status << std::endl; PdhCloseQuery(hQuery); return 1; } // 查询计数器值 status = PdhCollectQueryData(hQuery); if (status != ERROR_SUCCESS) { std::cout << "查询计数器值失败:" << status << std::endl; PdhCloseQuery(hQuery); return 1; } // 获取计数器值 status = PdhGetFormattedCounterValue(hCounter, PDH_FMT_LARGE, NULL, &counterValue); if (status != ERROR_SUCCESS) { std::cout << "获取计数器值失败:" << status << std::endl; PdhCloseQuery(hQuery); return 1; } // 输出计数器值 std::cout << "磁盘读速度:" << counterValue.largeValue << " 字节/秒" << std::endl; // 关闭查询 PdhCloseQuery(hQuery); return 0;}优化以上代码,这里会获取计数器值失败
时间: 2024-03-07 12:50:23 浏览: 165
您的代码存在两个问题:
1. 添加计数器时,计数器路径字符串中的反斜杠应该使用双反斜杠进行转义。
2. 获取计数器值时,应该先获取计数器值的大小,然后根据大小动态分配内存,最后再获取计数器值。这是因为 PDH_FMT_LARGE 格式的计数器值可能会非常大,超出常规的栈内存大小。
优化后的代码如下:
```C++
#include <iostream>
#include <pdh.h>
#pragma comment(lib, "pdh.lib")
int main()
{
PDH_STATUS status;
HQUERY hQuery;
HCOUNTER hCounter;
PDH_FMT_COUNTERVALUE buffer;
DWORD bufferSize = sizeof(buffer);
// 打开查询
status = PdhOpenQuery(NULL, 0, &hQuery);
if (status != ERROR_SUCCESS) {
std::cout << "打开查询失败:" << status << std::endl;
return 1;
}
// 添加计数器
status = PdhAddCounter(hQuery, L"\\PhysicalDisk(_Total)\\Disk Read Bytes/sec", 0, &hCounter);
if (status != ERROR_SUCCESS) {
std::cout << "添加计数器失败:" << status << std::endl;
PdhCloseQuery(hQuery);
return 1;
}
// 查询计数器值
status = PdhCollectQueryData(hQuery);
if (status != ERROR_SUCCESS) {
std::cout << "查询计数器值失败:" << status << std::endl;
PdhCloseQuery(hQuery);
return 1;
}
// 获取计数器值
status = PdhGetFormattedCounterValue(hCounter, PDH_FMT_LARGE, NULL, &bufferSize);
if (status != ERROR_SUCCESS) {
std::cout << "获取计数器值大小失败:" << status << std::endl;
PdhCloseQuery(hQuery);
return 1;
}
BYTE* buffer = new BYTE[bufferSize];
status = PdhGetFormattedCounterValue(hCounter, PDH_FMT_LARGE, NULL, &buffer);
if (status != ERROR_SUCCESS) {
std::cout << "获取计数器值失败:" << status << std::endl;
delete[] buffer;
PdhCloseQuery(hQuery);
return 1;
}
// 输出计数器值
std::cout << "磁盘读速度:" << ((PDH_FMT_LARGE*)buffer)->largeValue << " 字节/秒" << std::endl;
// 释放内存
delete[] buffer;
// 关闭查询
PdhCloseQuery(hQuery);
return 0;
}
```
这里使用动态内存分配来存储计数器值,避免了栈内存溢出的问题。同时,在获取计数器值前先获取计数器值的大小,保证能够正确地存储计数器值。
阅读全文