Calculating current (not average) download speed

陌路散爱 提交于 2019-12-09 13:24:52

问题


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.


回答1:


Given that "real-time" is unachievable, you should try to simulate it, by making the interval as small and precise as possible, and calculating the average over the interval, checking for 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 with your code:

  1. Only calculate Now once, use it twice.


来源:https://stackoverflow.com/questions/10507870/calculating-current-not-average-download-speed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!