How do I time a method execution in Java

Java 8Object Oriented ProgrammingProgramming

You should get a start time before making a call and end time after method execution. The difference is the time taken. 

Example

Live Demo

import java.util.Calendar;
public class Tester {
   public static void main(String[] args) {
      long startTime = Calendar.getInstance().getTimeInMillis();
      longRunningMethod();
      long endTime = Calendar.getInstance().getTimeInMillis();
      System.out.println("Time taken: " + (endTime - startTime) + " ms");
   }
   public static void longRunningMethod() {
      try {
         Thread.sleep(1000);
      } catch (InterruptedException e) {
         e.printStackTrace();
      }
   }
}

Output

Time taken: 1012 ms
raja
Published on 07-Feb-2018 10:07:57
Advertisements