Get elapsed time in Java



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
karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know


Advertisements