Google News
logo
Java Program to Calculate the Execution Time of Methods
You can calculate the execution time of methods in Java using the System.currentTimeMillis() method. Here's a simple example :
Program :
public class ExecutionTimeExample {
    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();

        // Call the method you want to measure
        myMethod();

        long endTime = System.currentTimeMillis();
        long executionTime = endTime - startTime;

        System.out.println("Execution time in milliseconds: " + executionTime);
    }

    public static void myMethod() {
        // Code of the method to be measured
        for (int i = 0; i < 1000000000; i++) {
            // Do nothing
        }
    }
}
Output :
Execution time in milliseconds: 4
In the above example, the System.currentTimeMillis() method is called twice - once at the beginning of the main() method to record the start time, and once after the method you want to measure (myMethod() in this case) has finished executing to record the end time. The difference between these two times is the execution time of the method.

Note that the execution time is measured in milliseconds, so for more precise measurements you may want to use System.nanoTime() instead of System.currentTimeMillis().