Wednesday, March 16, 2011

Better way to calculate time than using System.currentTimeMillis()

We are usually used to use System.currentTimeMillis() to calculate the time taken by some method or a piece of code. Ex:


  long startTime = System.currentTimeMillis();
        // Intelligent code which is taking time!
        long endTime = System.currentTimeMillis();


There is a better way to do this:




  import org.apache.commons.lang.time.StopWatch;

  StopWatch timer = new StopWatch();
        timer.start();
  // Intelligent code which is taking time!
  timer.stop();

  log.info("Time taken by load process: " + timer.getTime() + "  milliseconds.");

StopWatch is part of apache's commons-lang jar.

No comments:

Post a Comment