How to calculate method execution time in Java (using System.currentTimeMillis())


Friends the following udemy course created by me;

      Click here to attend Spring Framework 4.x and certification course with a discount

Spring Framework and Core Spring Certification Udemy course with discount
Spring Framework and Core Spring Certification Udemy course with a discount coupon

Here you can find a code example for calculating the execution time of a method;


package methodexecutiontimer;

/**
*
* @author tunatore
*/
public class MethodExecutionTimer {

public static void main(String[] args) {

  long start = System.currentTimeMillis();
  heavyMethod();
  long end = System.currentTimeMillis();
  System.out.println("Method execution total time"
  + " in seconds ==> " + (end - start) / 1000 + " seconds");

}

public static void heavyMethod() {

  for (int i = 1; i < 5; i++) {
  try {
      Thread.sleep(i * 1000); // * 1000 makes it second 1*1000 = 1 second
  } catch (InterruptedException ex) {
  ex.printStackTrace()
  }

 }
}
}

 

Program output;

run:
Method execution total time in seconds ==> 10 seconds
BUILD SUCCESSFUL (total time: 10 seconds)

Advertisements

2 thoughts on “How to calculate method execution time in Java (using System.currentTimeMillis())

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s