Tuesday, August 2, 2022

How to measure elapsed time of a method in Java

There are times we need to compute how much time is elapsed while executing a certain task. To compute elapsed time we can think something like below.

public class ElapsedTimeDemo {
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
doSomething();
long endTime = System.currentTimeMillis();
System.out.println("Elapsed time = "+ (endTime - startTime));
}
public void doSomething() {
}
}

This code keeps track of start time of function execution and end time once the execution is complete. The difference between start time and end time gives us the elapsed time. This looks good. The only problem is that for start time and end time we are depending upon the system clock. Because of the clock skew system clock tends to drift away from the actual time. To make the system clock sync usual practice is computer connects to a time server and adjusts its own clock. While adjusting the system clock it may be set forward or backward based on the drift. This can cause some issues in the above program. If the clock is getting adjusted while the method execution of doSomething(), we will get the end time which can be either before or after the real end time. This makes the elapsed time calculation faulty.
To make the correct elapsed time calculation consider the below program.

public class ElapsedTimeDemo {
public static void main(String[] args) {
long startTime = System.nanoTime();
doSomething();
long endTime = System.nanoTime();
System.out.println("Elapsed time = "+ (endTime - startTime));
}
public void doSomething() {
}
}

Here instead of currentTimeMillis() we are using nanoTime(), Nano time comes from a JVM monotonic clock. A monotonic clock means it starts with a fixed origin, let's assume it's a counter that starts from 0 when JVM starts it keeps on incrementing. At any point in time counter value will not make much sense in absolute terms. In elapsed time calculation this is useful. And this doesn't get adjusted like a system clock. 

References