How do I time a method execution in Java


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

Updated on: 25-Feb-2020

728 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements