Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find out which method is taking much time?

One of my component is taking too much time to execute. It calls lots of services which in turn calls many dao methods. Now, is there any way to get the time taken by each method it is calling.
I don't want to write System.currentmillis before and after each method to calculate time taken as there are too many methods.
I think i may need to use interceptors or may be any profiler can do that. I am not sure, please help.

like image 699
Rakesh Juyal Avatar asked Feb 28 '11 07:02

Rakesh Juyal


People also ask

How to find time taken by each method in Java?

The currentTimeMillis() method returns the current time in milliseconds. To find the elapsed time for a method you can get the difference between time values before and after the execution of the desired method. The nanoTime() method returns the current time in nano seconds.

How do I know where a method is used in eclipse?

Right click and select References > Project or References > Workspace from the pop-up menu. Show activity on this post. This will show you a Search view containing the hierarchy of class and method which using this method.

How do you stop a time execution in Java?

Using a Loop long start = System. currentTimeMillis(); long end = start + 30 * 1000; while (System. currentTimeMillis() < end) { // Some expensive operation on the item. } Here, the loop will break if the time has surpassed the limit of 30 seconds.


2 Answers

Use jvisualvm which should come with JDK (if I remember correctly). It's a GUI for your JVM, and has really nice functions. Check out its features there are some screenshots as well...

And you can follow these steps to integrate it as launcher in eclipse Steps to integrate in eclipse

like image 173
posdef Avatar answered Sep 30 '22 00:09

posdef


Don't look at it as measuring time to find the problem.

Use its slowness to expose it. Just use the same method you would if it were an infinite loop.

That is, pause it a few times while it's being slow, and each time inspect the call stack of each thread. The guilty methods and lines of code will appear on multiple samples. Check the last paragraph of this post.

Here's more on how it works.

like image 38
Mike Dunlavey Avatar answered Sep 30 '22 00:09

Mike Dunlavey