Get elapsed time in Java

Java 8Object Oriented ProgrammingProgramming

To get the elapsed time, first get the start time.

long start = System.nanoTime();

Now, we will get the end time after pausing for 5 seconds.

long end = System.nanoTime();

For the elapsed time, find the difference between end and start.

long elapsed = end - start;

Example

 Live Demo

import java.util.concurrent.TimeUnit;
public class Demo {
 public static void main(String[] args) throws InterruptedException {
    long start = System.nanoTime();
    TimeUnit.SECONDS.sleep(5);
    long end = System.nanoTime();
    long elapsed = end - start;
    System.out.println("Execution time (nanoseconds) = " + elapsed);
 }
}

Output

Execution time (nanoseconds) = 5000820351
raja
Published on 12-Dec-2018 08:23:23
Advertisements