Java Program to Measure Elapsed Time

Write a Java program to measure elapsed time using the System currentTimeMillis method. The currentTimeMillis method returns the elapsed time using wall clock time.

package NumPrograms;

public class ElapsedTime1 {
	public static void main(String[] args) throws Exception {
		
		long startTime = System.currentTimeMillis();
		
		for(int i = 0; i < 6; i++)
		{
			Thread.sleep(100);
		}
		
		long endTime = System.currentTimeMillis();
		
		double elapsedtime = (endTime - startTime) / 1000.0;
		
		System.out.println("Elapsed Time = " + elapsedtime);
	}
}
Java Program to Measure Elapsed Time

Java program to measure elapsed time using the System nanoTime method. The nanoTime method returns the result in nanoseconds.

package NumPrograms;

public class Example2 {

	public static void main(String[] args) throws Exception {
		
		long startTime = System.nanoTime();
		
		for(int i = 0; i < 5; i++)
		{
			Thread.sleep(100);
		}
		
		long endTime = System.nanoTime();
		
		double elapsedtime = (endTime - startTime) / 1000.0;
		
		System.out.println(elapsedtime);
	}
}
513317.972

In Java, the Instant class represents the instance of the timeline. The Java Instant now method returns the current timestamp, and we used that method in this program to measure the elapsed time.

package NumPrograms;

import java.time.Duration;
import java.time.Instant;

public class Example3 {

	public static void main(String[] args) throws Exception {
		
		Instant stTm = Instant.now();
		
		for(int i = 0; i < 5; i++)
		{
			Thread.sleep(100);
		}
		
		Instant edTm = Instant.now();
		
		double elapsedtime = Duration.between(stTm, edTm).toMillis();
		
		System.out.println(elapsedtime);
	}
}
509.0