我正在尝试获取WebClient下载文件的当前下载速度,但是当我使用我非常确定应该解决的公式时:
Stopwatch.Stop();
double msElapsed = Stopwatch.Elapsed.TotalMilliseconds;
int bytesDownloaded = (int)e.BytesReceived - lastBytesDownloaded;
double downloadSpeed = (double)bytesDownloaded / (msElapsed / 1000);
lastBytesDownloaded = (int)e.BytesReceived;
Stopwatch.Restart();
当秒表是我在启动文件下载时启动的秒表时,lastBytesDownloaded是一个类变量,这都在downloadProgressChanged事件中,但是下载速度与实际情况相差很大。
例如,如果我以500kb / s的速度下载文件,它将迅速从(例如)10kb / s快速跳转到50mb / s。
通过对其进行一些编辑,我可以获得准确的平均下载时间:
double sElapsed = Stopwatch.Elapsed.TotalSeconds;
int bytesDownloaded = (int)e.BytesReceived;
double downloadSpeed = bytesDownloaded / sElapsed;
但这不是我想要的。如何为当前下载速度获得更稳定的读数?
答案 0 :(得分:2)
您需要在更长的时间内smooth数据。例如,不要仅根据最后一次测量报告当前下载速度;使用a(可能是weighted)moving average代替。
死的简单例子:
var measurements = 0, maxDataPoints = 5;
var dataPoints = new double[maxDataPoints];
然后:
Stopwatch.Stop();
double msElapsed = Stopwatch.Elapsed.TotalMilliseconds;
int bytesDownloaded = (int)e.BytesReceived - lastBytesDownloaded;
lastBytesDownloaded = (int)e.BytesReceived;
double dataPoint = (double)bytesDownloaded / (msElapsed / 1000);
dataPoints[measurements++ % maxDataPoints] = dataPoint;
double downloadSpeed = dataPoints.Average();
Stopwatch.Restart();