0

So I'm designing a download manager using java, I need to show the download speed to the user.
below is the code I've used to find the download speed in KB/s but I don't think it's measuring download speed correctly. it's measuring my download speed pretty inaccurately from 5 KB/s to 200000 KB/s which is weird, my real download speed is approximately 500 KB/s.
MAX_BUFFER_SIZE is 16384.

   while (status == CURRENT) {
     /* Size buffer according to how much of the
        file is left to download. */
     byte buffer[];
     if (sizeOfFile - downloadedSize > MAX_BUFFER_SIZE) {
         buffer = new byte[MAX_BUFFER_SIZE];
     } else {
         buffer = new byte[sizeOfFile - downloadedSize];
     }

     // Read from server into buffer and measuring download speed.
     Long t1 = System.nanoTime();
     int read = stream.read(buffer);
     Long t2 = System.nanoTime();
     downloadSpeed = ((double) read / (double)(t2 - t1)) * 1000000;
     System.out.println(downloadSpeed);
     if (read == -1)
         break;

     // Write buffer to file.
     file.write(buffer, 0, read);
     downloadedSize += read;
     publish(downloadedSize);
     while (status == PAUSED) {
         Thread.sleep(1);
     }

 }

I can't figure out what's wrong with my method.

Thanks in advance.

Mahdi Ghajary
  • 2,717
  • 15
  • 20
  • You might want to average the calculation over a longer time instead of every `stream.read()` call. – Progman May 29 '18 at 17:16

1 Answers1

0

a fairly good alternative is to calculate download speed after certain number of while loops. for example in my program case after 30 while loops download speed is shown to the user using formula (size(bytes) /time (ns) * 10^6) in KB/s.

Mahdi Ghajary
  • 2,717
  • 15
  • 20