I'm writing a program that downloads stuff from the internet. While the program is working fine, I want to get one critical part reviewed. I use System.Diagnostics.StopWatch object to measure the time taken for the ns (NetworkStream) object to read the bytes in buffer. I then divide the number of elapsed seconds in stopwatch by number of bytes received to calculate the speed of my download in KBPS.
However, this method is giving me some extraordinarily large speeds (in excess of 8000KBPS), whereas I know that my internet bandwidth is not that fast. Is there anything wrong with this method? If not, then what is the correct way of getting the download speed? Here is my code:
while(true) //(bytesToRead>0)
{
sw.Start();
int n = ns.Read(buffer, 0, buffer.Length);
sw.Stop();
Speed = (float)n / sw.Elapsed.TotalSeconds;
if (n==0)
break;
fs.Write(buffer,0,n);
BytesRead+=n; //TODO: Persist the bytesRead object somewhere, so that it can be taken back for resumes
bytesToRead -= n;
OnProgress(this,new System.EventArgs());
if (Status == DownloadStatusEnum.Paused) break;
}
No comments:
Post a Comment
Thanks for your comments