views:

40

answers:

1

I want to know how long it takes a particular page to render, where are the various parts in the Spring MVC framework that I can start and stop my timer?

BTW, what java class should I use to get the most accurate time in milliseconds?

+5  A: 
  • Create a javax.servlet.Filter and map it in web.xml above all other filters. In the doFilter(..) place your coutner code around chain.doFilter(request, response)

  • Either use System.currentTimeMillis, or System.nanoTime() (more accurate), or perf4j.

This will show you how much time did it take for the server to generate the response. If you want to see the full loading time of the page as the client sees it, install FireBug on firefox.


A note on how a Filter operates. A request comes in, and is passed as argument to the first filter in the chain. Now the filter may decide to proceed the execution, or to stop it. If it choses to proceed, it invokes .chain.doFilter(..). Now the same happens with all defined filters for that resource, and ultimately the flow reaches the target Servlet (in this case - the DispatcherServlet). When the doGet(..) / doPost(..) method completes, the program flow, logically, returns to the caller - i.e. the last filter in the chain. When it completes - the program flow returns to the one above, until they reach the first filter which has called chain.doFilter(..). That is the line where you put your timing calculations. When the first filter returns, the flow goes to the servlet container internals, and soon the response is sent to the browser. So, your code will be:

public void doFilter(ServletRequest request,
   ServletResponse response, FilterChain chain) {

    long start = System.nanoTime();
    chain.doFilter(request, response);
    long end = System.nanoTime();
    // log end-start
}
Bozho
I will need 2 filters, one on the very top and one on the very bottom then no?
Blankman
no. place the calculations _around_ `chain.doFilter(..)` - it starts the whole process, and after it the page is ready.
Bozho
I guess I don't understand filters, how can a single filter know how long it will take? is it like the hitcounter sample here? http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/Servlets8.html
Blankman
I thought filter#1 fires, then filter#2 fires, etc. How can filter#1 know the length of execution of all other filters?
Blankman
You filter code should be something like: start=System.currentTimeMillis; chain.doFilter(...); end=System.currentTimeMillis; /* save end-start somewhere */. All other filters and the actual page render is done inside doFilter(...)
andcoz
@Blankman see updated
Bozho
+100 thanks ALLOT bozho! that cleared up allot of confusion.
Blankman
If you want to measure *elapsed* time, you should indeed use `nanoTime()`. See Kevin's [answer](http://stackoverflow.com/questions/1770010/how-do-i-measure-time-elapsed-in-java/1776053#1776053).
Pascal Thivent