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 elapsed time in nanoseconds.

package NumPrograms;

public class ElapsedTime2 {

	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("Elapsed Time = " + elapsedtime);
	}
}
Elapsed Time = 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 ElapsedTime3 {

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