Java Program to Calculate the Execution Time of Methods

In this java program, we will learn to calculate the execution time of a methods. In Java, you can calculate the execution time of a method by using the System.nanoTime() method. The System.nanoTime() method returns the current value of the most precise available system timer, in nanoseconds.

Here is an example of how you can use the System.nanoTime() method to calculate the execution time of a method.

public class ExecutionTimeExample {
    public static void main(String[] args) {
        long startTime = System.nanoTime();
        // call the method to be measured here
        someMethod();
        long endTime = System.nanoTime();
        long duration = (endTime - startTime);
        System.out.println("Execution time of someMethod() 
            in nano seconds : " + duration);
    }

    public static void someMethod() {
        // some code here
    }
}

In this example, the main method first calls the System.nanoTime() method to get the current time in nanoseconds and assigns it to the startTime variable. Then, the method someMethod() is called, after which the System.nanoTime() method is called again and the value is assigned to the endTime variable. Finally, the execution time is calculated by subtracting the start time from the end time, and the result is printed in nanoseconds.

You can also convert the execution time to other units like milliseconds or seconds.

long durationInMilliSec = TimeUnit.NANOSECONDS.toMillis(duration);
long durationInSec = TimeUnit.NANOSECONDS.toSeconds(duration);

It's important to note that the precision of the System.nanoTime() method may vary depending on the underlying hardware and operating system. It's also important to note that System.currentTimeMillis() is less precise than System.nanoTime() and it's measured in milliseconds.