Depending on what you need, you could simply measure the time needed to process the request:
class ResponseWrapper<T> {
public final Long generationTime;
public final T response;
public ResponseWrapper(final Long generationTime, final T response) {
this.generationTime = generationTime;
this.response = response;
}
}
@...
public ResponseWrapper<HelloWorld> helloWorld(...) {
long startTime = System.currentTimeMillis();
// process the request
long elapsedTime = System.currentTimeMillis() - startTime;
return new ResponseWrapper<HelloWorld>(elapsedTime , new HelloWorld(...));
}
Or, if you need some more universal solution, use filters from Servlet API:
public class GenerationTimeFilter implements Filter {
...
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) {
long startTime = System.currentTimeMillis();
chain.doFilter(req, res);
long elapsedTime = System.currentTimeMillis() - startTime;
}
}
To see how to modify a ServletResponse
inside filter, see this question: Looking for an example for inserting content into the response using a servlet filter
Just keep in mind, that this type of measurement will not give the final user the time he/she had to wait to get the response. Your application server will need a few miliseconds to handle raw HTTP request/response processing, not to mention network latency.