2

我正在尝试获取 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();

Stopwatch 是我在开始下载文件时开始的秒表,lastBytesDownloaded 是一个类变量,这都在 downloadProgressChanged 事件中,但是下载速度与实际情况相差很大。

例如,如果我以 500kb/s 的速度下载文件,它会完全随机地从(例如)10kb/s 快速跳转到 50mb/s。

我可以通过对其进行一些编辑来获得准确的平均下载时间:

double sElapsed = Stopwatch.Elapsed.TotalSeconds;
int bytesDownloaded = (int)e.BytesReceived;
double downloadSpeed = bytesDownloaded / sElapsed;

但这不是我想要的。如何获得当前下载速度的更稳定读数?

4

1 回答 1

2

您只需要在更长的时间内平滑数据。例如,不要仅根据上次测量报告当前下载速度;改用(也许是加权的)移动平均线。

死简单的例子:

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();
于 2013-10-06T19:26:03.150 回答