【问题标题】:Calculating Download Speed计算下载速度
【发布时间】:2012-08-11 05:55:25
【问题描述】:

我正在下载一个文件,但也尝试确定以 KBps 为单位的下载速度。我想出了一个方程式,但它给出了奇怪的结果。

    try (BufferedInputStream in = new BufferedInputStream(url.openStream());
        FileOutputStream out = new FileOutputStream(file)) {
        byte[] buffer = new byte[4096];
        int read = 0;
        while (true) {
            long start = System.nanoTime();
            if ((read = in.read(buffer)) != -1) {
                out.write(buffer, 0, read);
            } else {
                break;
            }
            int speed = (int) ((read * 1000000000.0) / ((System.nanoTime() - start) * 1024.0));
        }
    }

它给了我 100 到 300,000 之间的任何值。我怎样才能让它给出正确的下载速度?谢谢

【问题讨论】:

  • nanoTime 很少接近准确。下载时或下载完成后是否需要报告下载速度?
  • @SoboLAN 下载时。除了 nanoTime,我还能使用什么?我认为currentTimeMillis 也行不通。

标签: java stream


【解决方案1】:

您没有检查您的 currentAmmount 和 previousAmount 文件下载量。

例子

int currentAmount = 0;//set this during each loop of the download
/***/
int previousAmount = 0;
int firingTime = 1000;//in milliseconds, here fire every second
public synchronyzed void run(){
    int bytesPerSecond = (currentAmount-previousAmount)/(firingTime/1000);
    //update GUI using bytesPerSecond
    previousAmount = currentAmount;    
}

【讨论】:

  • 你能详细说明你的代码吗?我的意思是,你能发布完整的代码吗?
【解决方案2】:

首先,您正在以非常短的间隔计算read() 时间 + write() 时间,结果将根据 writes() 的(磁盘缓存)刷新而有所不同。 将计算放在read() 之后

其次,您的缓冲区大小(4096)可能与 tcp 缓冲区大小不匹配(您的最终较小),因此某些读取会非常快(因为它是从本地 TCP 缓冲区读取的)。使用Socket.getReceiveBufferSize() 并相应地设置缓冲区的大小(假设是 TCP recv buf 大小的 2*)并在计算之前将其填充到 嵌套循环中直到满

【讨论】:

    猜你喜欢
    • 2011-05-16
    • 2010-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-02
    • 2012-05-17
    • 2019-12-29
    • 1970-01-01
    相关资源
    最近更新 更多