As developers, we may need to measure the execution time of specific methods to identify their performance and optimize the code. In this article, we will see how to time profile Java method execution.

Java’s System library has a method called currentTimeMillis() which can used to time profile the method execution. This method returns the current time in milliseconds since the epoch(January 1, 1970).

So, we can easily calculate the elapsed time by capturing the current time before and after calling the method and analyzing the method’s performance.

Profiling the method execution

To begin, import the necessary classes, choose the method you want to profile and add the timing logic.

Following is an example of how to profile a method using System.currentTimeMillis():

import java.util.concurrent.TimeUnit;

public class MethodProfilerExample {
    public static void main(String[] args) {
        MethodProfilerExample profiler = new MethodProfilerExample();
        
        long startTime = System.currentTimeMillis();
        
        // Call the method you want to profile
        profiler.someMethod();
        
        long endTime = System.currentTimeMillis();
        
        long elapsedTime = endTime - startTime;
        System.out.println("Elapsed Time: " + elapsedTime + " milliseconds");
    }
    
    // Method to profile
    private void someMethod() {
        // Your method implementation here
    }
}

Convert Milliseconds to Seconds

If you want to display the elapsed time in seconds instead of milliseconds, you can convert it using TimeUnit.SECONDS.convert().

long elapsedTimeInSeconds = TimeUnit.SECONDS.convert(elapsedTime, TimeUnit.MILLISECONDS);
System.out.println("Elapsed Time: " + elapsedTimeInSeconds + " seconds");

Note: For more precise measurements, especially for short method executions, you can use System.nanoTime(). It returns the current time in nanoseconds, which provides higher accuracy than System.currentTimeMillis().

There are also several profiling tools available in the market such as VisualVM, YourKit Java Profiler, and JProfiler. These profiling tools can give us more detailed insights into method execution times, memory usage, and other performance-related metrics.

References:

https://docs.oracle.com/javase/8/docs/api/java/lang/System.html

https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/System.html

Categorized in:

Tagged in: