In my download manager application, I'm using the code below to calculate the current transfer rate:
TimeSpan interval = DateTime.Now - lastUpdateTime;
downloadSpeed = (int)Math.Floor((double)(DownloadedSize + cachedSize - lastUpdateDownloadedSize) / interval.TotalSeconds);
lastUpdateDownloadedSize = DownloadedSize + cachedSize;
lastUpdateTime = DateTime.Now;
This mostly works the way I want (I'm updating the speed every 4 seconds or so), but there are always some crazy spikes in the download rate as it fluctuates. My average download speed is around 600 kB/s, and sometimes it shows 10.25 MB/s or even negative values like -2093848 B/s. How could this be?
What is the best way to calculate real-time download rate? I'm not interested in the average rate (DownloadedSize / TimeElapsed.TotalSeconds), because it doesn't give realistic results.