ConfusionMaster
ConfusionMaster

Reputation: 19

Need Help on Calculating Java method performance

I got into a situation that I have to provide each and every method performance in my code in time taken.

It is a multi layered application and I have to provide for each level. Like

Class A.methodA()
{
    Class B.methodB()
      {
          Class C.methodC()
           {
               //Time Taken 30 sec
            }
          //Time Taken 40 secs
        }
     //Time Taken 50 secs
}

Whole operation completed in 50 secs.

This is how I should provide a report. Is there any framework or easy way than manually tracking start time and stop time of each method? As I am new to java development, finding bit difficult to do this in easily.

Upvotes: 0

Views: 69

Answers (3)

Ivan
Ivan

Reputation: 3836

Please note that whatever kind of profiling you'll use, it will affect the results of your app's performance. Sometimes the influence is small, sometimes it will be noticable.

The easiest thing to do is to try connecting to your application with jvisualvm (it's bundled with jdk) or any other profiler for java. Here's example of what that can show you.

jvisualvm method profiling

Upvotes: 0

lukeg
lukeg

Reputation: 4399

The tool you are looking for is called "profiler".

Upvotes: 0

S. Kaczor
S. Kaczor

Reputation: 401

Not sure what you mean by this code you've provided, since it doesn't look like valid java code (maybe you're confusing classes with methods?) The simplest solution is to use System.currentTimeMillis(), here is some simple example:

public class Main {
    public static void main(String[] args) throws IOException {
        long t1 = System.currentTimeMillis();
        //some code you want to check
        doOtherWork();
        long t2 = System.currentTimeMillis();
        System.out.println("Main time: " + (t2-t1));

    }

    public static void doOtherWork(){
        long t1 = System.currentTimeMillis();
        //some code you want to check
        evenMoreWork();
        long t2 = System.currentTimeMillis();
        System.out.println("doOtherWork time: " + (t2-t1));
    }

    public static void evenMoreWork(){
        long t1 = System.currentTimeMillis();
        //some code you want to check
        long t2 = System.currentTimeMillis();
        System.out.println("evenMoreWork time: " + (t2-t1));
    }
}

Remember that time spent in method main will also include time spent in all the methods that it called.

Upvotes: 1

Related Questions