Really confused with bandwidth calculation formula.
Referring to the bandwidth detection question Check the bandwidth rate in Android i am trying to calculate bandwidth as following.
long startTime = System.currentTimeMillis();
HttpResponse response = httpclient.execute(httppost);
HttpEntity httpEntity = response.getEntity();
long contentLength = httpEntity.getContentLength();
long endTime = System.currentTimeMillis();
float bandwidth = contentLength / ((endTime-startTime) / 1000); // In the refereed question it is "((endTime-startTime) * 1000)" don't know why multiplication.
What i need is current bandwidth in bits (not bytes or kbytes). I don't know using above formula if it is calculating bandwidth in bytes or bits.
also if download time is 0 seconds then what should be the bandwidth is it downloaded content length. can someone please suggest correct formula to calculate bandwidth in bits.
First of all for precision's sake, you should use 1000.0
to convert to seconds since you are assigning your bandwidth to a float
variable:
float bandwidth = (contentLength / (endTime-startTime)) / 1000.0;
Now since your contentLength is measured in bytes, you need to convert to bits (Kb, Mb, etc). There are 8 bits to each byte and socontentLength*8
converts bytes to bits.
Kilo->Mega->Giga ->... scale conversion for the unit of bits is on the order of 1000
which means converting bits to Megabits requires a division by 1000*1000
. All this put together should yield:
int bits = contentLength * 8;
int megabits = contentLength / (1000*1000); //Megabits
float seconds = endTime-startTime / 1000.0;
float bandwidth = (megabits / seconds); //Megabits-per-second (Mbps)
EDIT #1: If bandwidth is denominated by Bytes/Time (like KB/s for example), scale conversion is on the order of 1024
int bytes = contentLength;
int kilobytes = contentLength / 1024; //Kilobytes
EDIT #2: The definition of "Mega" and "Kilo" etc. when talking in terms of bandwidth can be somewhat ambiguous I am realizing. Often times 1024
(210) and 1000
(103) may be used interchangeably (most likely an accident). For many cases 1024
may be favored as the order of magnitude when calculating bandwidth as memory storage space on computers is measured in base 2. However network bandwidth is usually controlled by the clock speed of a CPU which regulates the transmission of bits, and this rate is measured in hertz (MHz to be exact) which is on the order of magnitude of 1000
, not 1024
. However in most cases, these two numbers are close enough to not produce significant error.