Write a Java Program to Calculate the Execution Time of Methods

As a Java programmer, it’s essential to optimize the performance of your code, especially when dealing with large datasets or complex algorithms.

One way to achieve this is by measuring the execution time of your methods.

In this tutorial, we’ll cover how to calculate the execution time of methods in Java.


Measuring Execution Time in Java

Java provides several ways to measure the execution time of a method.

One of the most straightforward ways is to use the System.currentTimeMillis() method, which returns the current time in milliseconds since the epoch (January 1, 1970, 00:00:00 GMT).

Here’s an example:

long startTime = System.currentTimeMillis();

// your method code goes here

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

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

In the code above, we use the startTime variable to store the current time before executing our method and the endTime variable to store the current time after executing our method.

Then, we calculate the execution time by subtracting the start time from the end time.

Another way to measure execution time in Java is by using the System.nanoTime() method, which returns the current time in nanoseconds.

Here’s an example:

long startTime = System.nanoTime();

// your method code goes here

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

System.out.println("Execution time: " + executionTime + " nanoseconds");

In this example, we use the startTime variable to store the current time in nanoseconds before executing our method and the endTime variable to store the current time in nanoseconds after executing our method.

Then, we calculate the execution time by subtracting the start time from the end time.


Conclusion

Measuring the execution time of methods is essential for optimizing the performance of your code.

In this tutorial, we covered two ways to measure execution time in Java: using System.currentTimeMillis() and System.nanoTime().

These methods are easy to use and provide accurate results.

By measuring the execution time of your methods, you can identify performance bottlenecks and improve the overall efficiency of your code.