Wednesday 11 November 2015

Java: Calculate method execution time


In this post, I am going to explain how to calculate method execution time in java. Common mistake java coders do while calculating method execution time is by using ‘System.currentTimeMillis()’.

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Test {
  public static void processData(){
    try {
      Thread.sleep(3000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
  
  public static void main(String args[]){
    long time1 = System.currentTimeMillis();
    processData();
    long time2=System.currentTimeMillis();
    
    System.out.println("Total time taken is "+ (time2-time1)/1000 + " seconds");
    
    Date date = new Date(time2);
    DateFormat formatter = new SimpleDateFormat("MMM dd,yyyy HH:mm:ss:SSS");
    String dateFormatted = formatter.format(date);
    
    System.out.println("Method finished at "+ dateFormatted);
    
    
  }
}


Output
Total time taken is 3 seconds
Method finished at Nov 10,2015 12:02:02:959


One problem with System.currentTimeMillis() is, it converts the system time into milliseconds. It depends on system time. What if some body change the system time during the execution of method, obviously you will get wrong results. So we require a way to safely measure elapsed time in a program, that doesn’t depend on the system time.

Better alternative is to use System.nanoTime method. System.nanoTime() return the current value of the running the Java Virtual Machine's high-resolution time source, in nanoseconds. Documentation clearly mentions that, it is not depend on system time.

public class Test {
  public static void processData() {
    try {
      Thread.sleep(3000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }

  public static void main(String args[]) {
    long time1 = System.nanoTime();
    processData();
    long time2 = System.nanoTime();

    System.out.println("Total time taken is " + (time2 - time1) /1000000000
        + " seconds");

  }
}


Output
Total time taken is 3 seconds

Note:
System.nanoTime() is monotonic, if and only if the underlying platform supports CLOCK_MONOTONIC. Please go through following bug for more details.


You may like


                                                 Home

No comments:

Post a Comment