C++使用PdhAddCounter获取特定进程网络收发速率
C++使用PdhAddCounter获取特定进程网络收发速率
在Windows平台上,我们可以利用性能计数器来监控进程的网络活动。本文将介绍如何使用PdhAddCounter函数获取特定进程的网络收发速率,并提供完整的C++代码示例。
步骤
- 获取进程实例ID: 使用
PdhLookupPerfNameByIndex函数,传入目标进程ID,获取对应的性能对象实例名称。2. 构造网络接口实例名称: 根据获取到的进程实例ID,拼接出网络接口性能计数器的完整路径。3. 创建性能查询: 使用PdhOpenQuery函数创建一个性能查询对象。4. 添加计数器: 使用PdhAddCounter函数将目标性能计数器添加到查询对象中。5. 收集数据: 使用PdhCollectQueryData函数收集性能数据。6. 格式化输出: 使用PdhGetFormattedCounterValue函数将收集到的数据格式化为可读格式。7. 关闭查询: 使用PdhCloseQuery函数关闭性能查询对象。
代码示例cpp#include
#pragma comment(lib, 'pdh.lib')
int main(){ PDH_STATUS pdhStatus; HQUERY hQuery; HCOUNTER hCounter; DWORD dwBufferSize = 0; TCHAR szInstanceName[256] = {0}; TCHAR szCounterPath[512] = {0}; PDH_FMT_COUNTERVALUE pdhValue;
// 获取进程的实例ID DWORD dwProcessId = 1234; // 替换为目标进程的ID pdhStatus = PdhLookupPerfNameByIndex(NULL, dwProcessId, szInstanceName, &dwBufferSize); if (pdhStatus != ERROR_SUCCESS) { std::cout << 'PdhLookupPerfNameByIndex failed with error code: ' << pdhStatus << std::endl; return 1; }
// 构造网络接口的实例名 _stprintf_s(szCounterPath, _T('\Process(%s)\IO Data Bytes/sec'), szInstanceName);
// 创建查询对象 pdhStatus = PdhOpenQuery(NULL, 0, &hQuery); if (pdhStatus != ERROR_SUCCESS) { std::cout << 'PdhOpenQuery failed with error code: ' << pdhStatus << std::endl; return 1; }
// 添加计数器 pdhStatus = PdhAddCounter(hQuery, szCounterPath, 0, &hCounter); if (pdhStatus != ERROR_SUCCESS) { std::cout << 'PdhAddCounter failed with error code: ' << pdhStatus << std::endl; return 1; }
// 查询计数器值 pdhStatus = PdhCollectQueryData(hQuery); if (pdhStatus != ERROR_SUCCESS) { std::cout << 'PdhCollectQueryData failed with error code: ' << pdhStatus << std::endl; return 1; }
pdhStatus = PdhGetFormattedCounterValue(hCounter, PDH_FMT_DOUBLE, NULL, &pdhValue); if (pdhStatus != ERROR_SUCCESS) { std::cout << 'PdhGetFormattedCounterValue failed with error code: ' << pdhStatus << std::endl; return 1; }
std::cout << 'Network data rate: ' << pdhValue.doubleValue << ' bytes/sec' << std::endl;
// 关闭查询对象 PdhCloseQuery(hQuery);
return 0;}
注意:
- 将代码中的
dwProcessId替换为你要监控的进程ID。*\Process(%s)\IO Data Bytes/sec表示进程的网络数据传输速率(字节/秒),你也可以根据需要修改为其他性能计数器路径。
希望本文能帮助你理解如何使用PdhAddCounter函数获取特定进程的网络收发速率。
原文地址: https://www.cveoy.top/t/topic/fSwi 著作权归作者所有。请勿转载和采集!