优化一下,获取计数器值会失败
时间: 2023-10-02 13:07:39 浏览: 54
下面是一个优化后的代码示例,包括了添加计数器实例和等待时间的设置,可以尝试使用这个代码来获取计数器值:
```
#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;
}
// 等待一段时间
Sleep(1000);
// 查询计数器值
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;
}
```
这里我们添加了一个等待时间,以等待计数器值的刷新。如果您使用的是自定义计数器,需要确保该计数器已经创建并且正在运行。您可以使用 Perfmon.exe 工具来查看计数器是否存在,并检查计数器名称和路径是否与代码中添加的计数器名称和路径一致。如果问题仍然存在,可以使用 PdhGetLastError 函数来获取更详细的错误信息。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)