Reputation: 1888
I have a Test class with a method called public void httpcall()
, I need to get the execution time of this method. In order to do this, I have used System.nanoTime()
before and after calling it. I get the execution time from that duration.
code snippet:
public class Test{
public void httpcall(){
try {
HttpResponse rs = HttpClientUtil.get("http://192.169.1.2:9090/plugins/restapi/v1/users/9223370580466120397/roster",RestOpenfire.ACCEPT, "8V9BUNA0f1gNQI3S");
} catch (Exception e) {
System.out.println("Error : "+e);
}
}
public static void main(String[] args) {
Test test=new Test();
long startTime = System.nanoTime();
test.httpcall();
long endTime = System.nanoTime();
long duration = (endTime-startTime);
System.out.println("Execution Time : "+duration);
}
}
I want to make an annotation like @Time
that gives an execution time of the method, something like ..
@Time
public void httpcall(){
try {
HttpResponse rs = HttpClientUtil.get("http://192.169.1.2:9090/plugins/restapi/v1/users/9223370580466120397/roster",
RestOpenfire.ACCEPT, "8V9BUNA0f1gNQI3S");
} catch (Exception e) {
System.out.println("Error : " + e);
}
}
How could I do this?
Upvotes: 1
Views: 551
Reputation: 2007
You can try to use aspectj which can either change your source code as part of your build, change your .class files in a process called weaving or change it on runtime.
https://mathewjhall.wordpress.com/2011/03/31/tracing-java-method-execution-with-aspectj/
Thought, it can be an overkill. Unless you have a huge system that will be hard to refactor, I recommend using template methods. That is,
abstract class Measurable
{
protected void abstract doWork();
public void execute(){
stopWatch = StopWatch.start();
doWork();
stopWatch.stop();
System.out.println(stopWatch.getTime());
}
}
class MyHttpClient extends Measurable
{
doWork(){
HttpResponse rs = HttpClientUtil.get("http://192.169.1.2:9090/plugins/restapi/v1/users/9223370580466120397/roster",RestOpenfire.ACCEPT, "8V9BUNA0f1gNQI3S");
}
}
public static void main(String[] args) {
MyHttpClient test=new MyHttpClient();
test.execute();
}
And all uses of MyHttpClient will call the execute() method.
Also note that I used StopWatch class, since it is more elegant and standard than using System.currentTimeMillis. https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/time/StopWatch.html
Upvotes: 2