How can I measure the file downloading time using servlets?

Serge Knystautas

[Note: this could mean servlet-as-client or servlet-as-server; we assume this is the servlet-as-server interpretation]

First start by creating a FileServlet... a servlet that takes a dir/filename as a parameter (either query string, post parameters, or extra path info). Get a File object handle to the data you want to download. Before you start writing data, capture the current time in a long primitive. Then write all data out, and at the end, get the current time again. Take the difference, and that was your transfer time. Here's some mockup code. note: do not implement this as it gives read access to your entire web root (including source of JSPs... figure out where you want to serve files from and change accordingly.

ServletOutputStream out = response.getOutputStream();
String filename = getServletContext().getRealPath(request.getQueryString());
FileInputStream fin = new FileInputStream(filename);
long start = System.currentTimeMillis();
byte data[] = new byte[1024];
int len = 0;
while ((len = > 0) {
    out.write(data, 0, len);
long stop = System.currentTimeMills();
log("took " + (stop - start) + "ms to download " + filename);
[N.B.: the above approach may not give the results you're looking for. It measures the amount of time spent on the server; however, many other factors can determine the perceived time spent by the client, including net lag and buffering. A more accurate approach would use JavaScript to do the following:
  1. Store the current time in a JavaScript variable
  2. Output random data of a known size
  3. At the end of that block, mark the time again and subtract as above
  4. Divide by data size to get transfer rate
Check out MSN's Bandwidth Speed Test for inspiration.


Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



About | Sitemap | Contact