Java Program to Calculate the Execution Time of Methods

Updated on December 4, 2024
Calculate the execution time of methods header image

Introduction

In Java programming, tracking the execution time of methods is crucial for performance tuning and optimization. Whether you're working on a simple app or a complex system, understanding how long your methods take to execute can help you identify bottlenecks and improve efficiency.

In this article, you will learn how to calculate the execution time of methods in Java using straightforward examples. Dive into several methods, including the use of System.nanoTime(), System.currentTimeMillis(), and the Java 8 Instant class.

Using System.nanoTime()

Overview of System.nanoTime()

  1. Recognize that System.nanoTime() provides the highest resolution (nanosecond level) timer for measuring how long a task takes in Java.
  2. Note that it is more suitable for measuring algorithm performance where precise measurement is necessary.

Example: Measure Using System.nanoTime()

  1. Define a method to be measured.

  2. Capture the start time before the method execution.

  3. Capture the end time after the method execution.

  4. Calculate the elapsed time by subtracting start time from end time.

    java
    public class ExecutionTimer {
        public static void methodToBeTimed() {
            // Simulated code
            try {
                Thread.sleep(1000);  // Simulate a delay
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    
        public static void main(String[] args) {
            long startTime = System.nanoTime();
            methodToBeTimed();
            long endTime = System.nanoTime();
            long duration = (endTime - startTime);
            System.out.println("Execution time in nanoseconds: " + duration);
        }
    }
    

    This program calculates the execution time of methodToBeTimed() using System.nanoTime(). The method simulates a process by sleeping for one second. The result is the time taken by the method in nanoseconds.

Using System.currentTimeMillis()

Overview of System.currentTimeMillis()

  1. Understand that System.currentTimeMillis() provides time in milliseconds since the UNIX epoch (00:00:00 UTC on January 1, 1970).
  2. It's generally used for measuring elapsed time in milliseconds.

Example: Measure Using System.currentTimeMillis()

  1. Implement a similar setup as with System.nanoTime(), but use System.currentTimeMillis() for less granular time measurements.

    java
    public class MilliTimer {
        public static void methodToBeTimed() {
            // Simulated code
            try {
                Thread.sleep(2000);  // Simulate a longer delay
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    
        public static void main(String[] args) {
            long startTime = System.currentTimeMillis();
            methodToBeTimed();
            long endTime = System.currentTimeMillis();
            long duration = (endTime - startTime);
            System.out.println("Execution time in milliseconds: " + duration);
        }
    }
    

    Here, instead of nanoseconds, the execution time is noted in milliseconds, which might be more appropriate for less time-sensitive measurements.

Using Java 8 Instant Class

Overview of the Instant Class

  1. Know that Java 8 introduced java.time.Instant which represents a moment on the timeline in UTC.
  2. It can be used to measure time with easy-to-read methods.

Example: Measure Using Instant Class

  1. Use Instant.now() to record start and end times.

  2. Calculate duration using Duration.between().

    java
    import java.time.Instant;
    import java.time.Duration;
    
    public class InstantTimer {
        public static void methodToBeTimed() {
            // Simulated code
            try {
                Thread.sleep(1500);  // Simulate a medium delay
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    
        public static void main(String[] args) {
            Instant start = Instant.now();
            methodToBeTimed();
            Instant end = Instant.now();
            Duration timeElapsed = Duration.between(start, end);
            System.out.println("Execution time: " + timeElapsed.toMillis() + " milliseconds");
        }
    }
    

    This example demonstrates the use of Instant and Duration classes to elegantly measure the execution time in milliseconds.

Conclusion

Measuring the execution time of methods in Java is essential for optimizing and fine-tuning application performance. Using System.nanoTime(), System.currentTimeMillis(), and Java 8's Instant class provides you with flexibility and precision, depending on your needs in specific scenarios. By applying these techniques, ensure your Java applications run efficiently, making the best use of system resources. Implement these strategies in your development process to maintain an effective performance measure.