Download speed calculation

I am downloading a file, but also trying to determine the download speed in KBps. I came up with an equation, but it gives strange results.

    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));
        }
    }

This gives me somewhere between 100 and 300,000. How can I get this to give the correct download speed? Thanks

+5
source share
2 answers

You are not checking your current account and previous file upload file.

Example

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
source

read() time + write() , ( ) (). read()

-, (4096), , tcp ( ), - ( TCP-). Socket.getReceiveBufferSize() (, 2 * TCP recv buf) .

0

All Articles