5

ファイルをダウンロードしていますが、ダウンロード速度を 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の間のどこかを与えています。これを正しいダウンロード速度にするにはどうすればよいですか? ありがとう

4

2 に答える 2

2

ファイルのダウンロードの 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;    
}
于 2012-08-11T06:01:36.513 に答える
0

read()まず、時間 +時間を非常に短い間隔で計算write()しているため、結果は write() の (ディスク キャッシュ) フラッシュによって異なります。Secondの直後に計算を入れるread()

と、バッファー サイズ (4096) はおそらく tcp バッファー サイズと一致しません (最終的にはあなたの方が小さくなります)。そのため、一部の読み取りは非常に高速になります (ローカル TCP バッファーから読み取られるため)。 . それに応じてバッファのサイズを使用Socket.getReceiveBufferSize() および設定し(たとえば、TCP recv buf サイズのサイズの 2 倍)、計算する前にいっぱいになるまでネストされたループに入れます。

于 2012-08-11T06:28:16.150 に答える