Java program to calculate the execution time of methods

ww‮itfigi.w‬dea.com

In Java, you can calculate the execution time of a method using the System.nanoTime() method. Here's an example program that demonstrates how to calculate the execution time of a method:

public class ExecutionTimeExample {
    public static void main(String[] args) {
        long startTime = System.nanoTime();
        methodToTime();
        long endTime = System.nanoTime();

        long duration = (endTime - startTime) / 1000000; // in milliseconds

        System.out.println("Execution time: " + duration + " ms");
    }

    public static void methodToTime() {
        // simulate some work
        for (int i = 0; i < 1000000; i++) {
            Math.sin(i);
        }
    }
}

In this program, we first call the System.nanoTime() method to get the start time before calling the methodToTime(). After the method call completes, we call the System.nanoTime() method again to get the end time. We then calculate the duration of the method call by subtracting the start time from the end time, and dividing by 1,000,000 to convert the duration from nanoseconds to milliseconds. Finally, we print the execution time.

In this example, we have a method called methodToTime() that simulates some work by calling the Math.sin() method in a loop. You can replace this with your own method to measure its execution time.

The output of the program should look like this:

Execution time: 11 ms

Note that the execution time may vary depending on the performance of your machine.