28 October 2011

Measuring Time to Minutest Precision With Guava

Other than profiling, have you ever encountered scenarios where you wanted to measure elapsed time from a predetermined past. A simple way of doing is to log the time (milliseconds or nanoseconds) into a long and then find the difference between two points. Here is a simple code.

public static void timer() throws Exception { 
long startMillis = System.currentTimeMillis(); 
for(int i = 0; i < 10; ++i) { 
Thread.sleep(1000);//equivalent to some work/logic 
long endMillis = System.currentTimeMillis(); 
System.out.println("Elapsed Time = " + (endMillis - startMillis));
// if i need to reset the start time, i need to do the following 
// startMillis = System.currentTimeMillis();
}  
}

If you are looking for only time difference between two points, you don't need to actually log the current time. It is enough if you start a clock (your own clock may be) at time t1 and stop it at time t2. If you want to measure time, you end up writing boiler plates. Guava has a little cute API for this.

Stopwatch is a simple API that mimics the functionality of a stopwatch. Here is the reincarnation of above code example.


public static void niceLittleAPI() throws Exception { 
Stopwatch stopWatch = new Stopwatch();  
stopWatch.start();  
for(int i = 0; i < 10; ++i) { 
Thread.sleep(1000);//equivalent to some work/logic  
System.out.println("Elapsed Time = " + stopWatch.elapsedMillis()); 
// if i need to reset the timer/clock, i need to do the following 
//stopWatch.reset(); 
// and my timer resets to zero
                                 // and if you want to stop the Stopwatch, just call
                                // stopWatch.stop();
}
What are the other advantages of using Stopwatch. I think it is an advantage of Stopwatch that it hides completely the mechanism it uses to keep time and in fact the user of the API is free to give his/her own Ticker.

Another nice addon is that you can get the elapsed time in days, hours, minutes, seconds, milliseconds, microseconds and nanoseconds which becomes very handy at times. A word of caution, Stopwatch is not thread safe and you have to figure it out how to make it thread-safe :-).

In order to understand the full power of Stopwatch, you may want to read Javadocs of Stopwatch, Timer and TimeUnit.

In my next post, we will see yet another Guava class and its use.

You may also want to check my previous post on Guava's Postconditions.

No comments: