目前计算(不平均)的下载速度 [英] Calculating current (not average) download speed

查看:220
本文介绍了目前计算(不平均)的下载速度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的下载管理器应用程序中,我使用下面的代码,以计算出当前传输速率:

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;

这主要是工作的方式我想(我更新每4秒左右的速度),但总是在下载速率一些疯狂的峰值,因为它波动。我的平均下载速度是约600 KB /秒,有时它显示10.25 MB / s或类似-2093848 B / S甚至负值。这怎么可能呢?

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?

什么是计算的实时下载速率的最佳途径?我不感兴趣的平均速率(DownloadedSize / TimeElapsed.TotalSeconds),因为它并没有给实际的结果。

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.

推荐答案

由于实时是无法实现的,你应该尝试模拟它,通过使间隔小和精确越好,计算平均在区间,检查代码中的理智。例如:

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. 仅计算现在,一旦使用两次。

这篇关于目前计算(不平均)的下载速度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆