- Instance is a java 8 datime time API object
- TimeUnit class which class sleep method indirectly class Thread.sleep method but we use TimeUnit class because it is more readable.
- We calculate the difference between instance using Duration class and print it at the end
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.TimeUnit;
public class CalculateExecutionTime {
public static void main(String[] args) throws InterruptedException {
Instant start = Instant.now();
TimeUnit.SECONDS.sleep(5);
Instant finish = Instant.now();
long timeElapsed = Duration.between(start, finish).toMillis()/1000; //in millis
System.out.println("Execution time in Seconds: "+timeElapsed);
}
}