How can I measure the file downloading time using servlets?
Created May 4, 2012
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.
-Alex]
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 = fin.read(data)) > 0) {
out.write(data, 0, len);
}
out.flush();
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:
Check out MSN's Bandwidth Speed Test for inspiration.