最近项目中需要实现一个网络测速的功能,把尝试到的几种方式总结一下。 开发环境是Visual Studio 2010。
一开始对网络测速这个功能有点误解,和当前网卡流量搞混了。毫不犹豫的找到了一个非常简单的方式,利用pdh.lib。这个库可以实现的功能可以参考Windows自带的工具perfmon.exe。在“Start”里搜索perfmon.exe可以看到。常见的CPU利用率,剩余内存,网络流量等都可以查到。
#include <iostream>
#include <Pdh.h>
#include <PdhMsg.h>
#pragma comment(lib,"pdh.lib")
int main()
{
HQUERY query;
PDH_STATUS status = PdhOpenQuery(NULL, NULL, &query);
if (status != ERROR_SUCCESS)
std::cout << "Open Query Error" << std::endl;
HCOUNTER counter;
counter = (HCOUNTER *)GlobalAlloc(GPTR, sizeof(HCOUNTER));
WCHAR CounterPathBuffer[PDH_MAX_COUNTER_PATH]=
L"\\Network Interface(Intel[R] Ethernet Connection [2] I219-V)\\Bytes Received/Sec"; //Use perfMon.exe, add monitor can get the right counter name.
status = PdhAddCounter(query, CounterPathBuffer, NULL, &counter);
if (status != ERROR_SUCCESS)
std::cout << "Add Counter Error" << std::endl;
PdhCollectQueryData(query);
Sleep(1000);
PdhCollectQueryData(query);
PDH_FMT_COUNTERVALUE pdhValue;
DWORD dwValue;
status = PdhGetFormattedCounterValue(counter, PDH_FMT_DOUBLE, &dwValue, &pdhValue);
if (status != ERROR_SUCCESS)
std::cout << "Get Value Error" << std::endl;
std::cout << pdhValue.doubleValue << std::endl;
PdhCloseQuery(query);
return 0;
}
实现很简单,可惜是错的,看到的当前经过网卡的流量,不是网速。
网速的测试只有利用文件下载,文件大小 / 下载时间 = 网络速度。偷懒又想走捷径,利用了Urlmon.lib里的URLDownloadToFile函数。
#include <Windows.h&