Get the elapsed time in seconds in Java

Hello Learners, today we are going to learn how to get the elapsed time in seconds in Java. But first of all, you need to understand what an elapsed time actually is.

Elapsed Time:

Elapsed time is the total time taken to complete an event by the time it has been started. For example, if you are writing code then elapsed time for that program is the time which is calculated from the start of execution till the execution ends.

There are multiple methods to calculate this:

  • currentTimeMillis() method
  • nanoTime() method
  • StopWatch class
  • Instant class

java Program to Get the Elapsed Time in Seconds:

You can do it using any of these methods. but here we are going to use the currentTimeMillis method. So, let’s see the code without wasting any time.

public class elapsed_time {
  public static void main(String[] args) throws Exception {

          long start_time = System.currentTimeMillis();
          
          for (int i = 0 ; i < 4 ; i++) {
             Thread.sleep(100);
          }
          
          long end_time = System.currentTimeMillis();
          float seconds = (end_time - start_time) / 1000F; 
          System.out.println("Elapsed time in seconds "+ seconds);
   }
}

OUTPUT:

Elapsed time in seconds 0.402
  • currentTimeMillis Method(): This method comes under the Java.lang package. The method returns the current time in milliseconds.
  • Under the main method, we created a variable start_time. It will hold the time value in long from where the execution of your code starts.
  • In the next line, we started a for loop. The loop stops the program for a hundred milliseconds in each iteration with Thread.sleep() method. Here we have given 4 iterations, you can give any number of iterations to get different outputs.
  • After the for Loop has been ended, we have another variable end_time. This variable is used to store the current time after all the statements have been executed.
  • At the end to calculate the execution time or the elapsed time subtract the start_time from the end_time. To convert the value in seconds divide it by thousand.

NOTE: If you want a high precision value then you can go for nanoTime() method. The nanoTime method returns the current time in nanoseconds.

Leave a Reply

Your email address will not be published. Required fields are marked *