Calculation of the current (not average) download speed

In my download manager application, I use 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; 

It basically works the way I want (I update the speed every 4 seconds or so), but there are always some crazy bursts of download speed 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 V / s. How could this happen?

What is the best way to calculate download speed in real time? I am not interested in the average speed (DownloadedSize / TimeElapsed.TotalSeconds), because it does not give realistic results.

+4
source share
1 answer

Given that "real time" is unattainable, you should try to simulate it by making the interval as small and accurate as possible, and calculate the average value of the interval by checking sanity in the code. For instance:

 DateTime now = DateTime.Now; TimeSpan interval = now - lastUpdateTime; timeDiff = interval.TotalSeconds; sizeDiff = DownloadedSize + cachedSize - lastUpdateDownloadedSize; speed = (int)Math.Floor((double)(sizeDiff) / timeDiff); lastUpdateDownloadedSize = DownloadedSize + cachedSize; lastUpdateTime = now; 

One difference of your code:

  • Calculate only once, use it twice.
+4
source

Source: https://habr.com/ru/post/1411412/


All Articles