Calculate Elapsed / Method Execution Time Using Java

 Posted On  | Yashwant Chavan 

Most of Time we need to calculate method execution time to keep eye on Method performance. Java provides simple way to calculate Method Execution timing.

There are several ways to calculate elapsed execution time using Java. By using System.currentTimeinMillis() or you can use System.nanoTime().These two methods which provides facility to measure elapsed or execution time of method.

To Calculate elapsed time of method execution, you need to find out start and end time in seconds or millisecond then calculate the difference between start and end time. Most of Java developers are usig System.currentTimeInMillis() which is there from early days of java versions.

But in java 1.5 they introduce new time measurement utility method System.nanoTime()

Find Out Elapsed time


import java.util.Random;

public class ExecutionExample {

    public static void main(String args[]) {

        long startTime = System.nanoTime();

        ExecutionExample executionExample = new ExecutionExample();

        long endTime = System.nanoTime();

        long elapsedTime = endTime - startTime;
        System.out.println("ElapsedTime Using System.nanoTime():- " + elapsedTime + "(nanoseconds)");

        startTime = System.currentTimeMillis();
        endTime = System.currentTimeMillis();

        elapsedTime = endTime - startTime;
        System.out.println("ElapsedTime Using System.currentTimeMillis:- " + elapsedTime + "(milliseconds)");


    public void callMe() {
        String collect[] = new String[1000000];
        for (int i = 0; i < 1000000; i++) {
            // Your Business Logic
            Random rn = new Random();
            collect[i] = String.valueOf(rn.nextInt());



Output may vary base on resources available (memory, processors etc)

ElapsedTime Using System.nanoTime():- 532081949(nanoseconds)
ElapsedTime Using System.currentTimeMillis:- 340(milliseconds)

© 2018

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0585 seconds.