[英]C#, Calculating Download Speed, Where's The Problem?
I want to calculate download speed as kbps (kb per second). 我想将下载速度计算为kbps(每秒kb)。 There's a problem in the code, it doesn't show actual speed.
代码中有问题,它没有显示实际速度。 And I'm really tired of this work.
我真的对这项工作感到厌倦。 Also, when using
(TotalDownloadSize / ElapsedTime)
formula it shows more realistic results but you know it will get average value and it will be stupidity. 同样,当使用
(TotalDownloadSize / ElapsedTime)
公式时,它显示的结果更真实,但您知道它将获得平均值并且将是愚蠢的。
It usually gives 4000 and it's basicly because of chunk 4096 when I set it to 128 that time I get 50/100/125 values. 通常给出4000,这基本上是因为块4096,当我将其设置为128时,我得到50/100/125值。
DateTime dlElapsed;
private delegate void UpdateProgessCallback(Int64 BytesRead, Int64 TotalBytes, Int32 CurrentBytes);
private void UpdateProgress(Int64 BytesRead, Int64 TotalBytes, Int32 CurrentBytes)
{
DateTime Elapsed = DateTime.Now;
var progress = Convert.ToInt32((BytesRead * 100) / TotalBytes);
var elaps = (Elapsed - dlElapsed).TotalSeconds;
long kbps;
if (elaps > 0)
{
kbps = Convert.ToInt64((CurrentBytes / elaps) / 1024);
updateLabelText(String.Format("Downloading ({0} kbps)...", kbps));
}
// Make progress on the progress bar
if (progress < progressBar1.Maximum)
{
progressBar1.Value = progress;
}
else
{
progressBar1.Value = progressBar1.Maximum;
}
dlElapsed = DateTime.Now;
}
private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
// Some stuff here...
int byteSize = 0;
byte[] downBuffer = new byte[4096];
FileStream strLocal= new FileStream(path, FileMode.Create, FileAccess.Write);
dlElapsed = DateTime.Now;
while ((byteSize = stream.Read(downBuffer, 0, downBuffer.Length)) > 0)
{
strLocal.Write(downBuffer, 0, byteSize);
this.Invoke(new UpdateProgessCallback(this.UpdateProgress),
new object[] { strLocal.Length, totalbyte, byteSize});
}
updateLabelText("Download complete!");
strLocal.Close();
}
}
So where's the problem? 那么问题出在哪里?
So where's the problem?
那么问题出在哪里?
You're coarsely sampling something that varies a lot. 您正在粗略地采样变化很大的东西。
Consider buffering measurements and averaging the last 5 or so. 考虑对测量结果进行缓冲,并平均最后5个左右的值。 Look for implementations of a "running average".
寻找“移动平均”的实现。
Well, my first comment would be that your code is not thread safe, so when you set dlElapsed = DateTime.Now;
好吧,我的第
dlElapsed = DateTime.Now;
是您的代码不是线程安全的,因此当您设置dlElapsed = DateTime.Now;
, it's not the same dlElapsed
value that UpdateProgress
is going to be checking. ,它与
UpdateProgress
将要检查的dlElapsed
值不同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.