Compute the elapsed time of an operation in Java


To compute the elapsed time of an operation in Java, we use the System.currentTimeMillis() method. The java.lang.System.currentTimeMillis() returns the current time in milliseconds.

Declaration −The java.lang.System.currentTimeMillis() is declared as follows −

public static long currentTimeMillis()

The method returns time difference in milliseconds between the current time and midnight, January 1, 1970 (UTC or epoch time).

Let us see a program to compute the elapsed time of an operation in Java −

Example

 Live Demo

public class Example {
   public static void main(String[] args) throws Exception {
      // finding the time before the operation is executed
      long start = System.currentTimeMillis();
      for (int i = 0; i <5; i++) {
         Thread.sleep(60);
      }
      // finding the time after the operation is executed
      long end = System.currentTimeMillis();
      //finding the time difference
      float msec = end - start;
      System.out.println(msec + " milliseconds");
      // converting it into seconds
      float sec= msec/1000F;
      System.out.println(sec + " seconds");
      // converting it into minutes
      float minutes=sec/60F;
      System.out.println(minutes + " minutes");
   }
}

Output

300.0 milliseconds
0.3 seconds
0.0050000004 minutes

Updated on: 26-Jun-2020

141 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements