Prashanth Babu

Ramblings on Hadoop Ecosytem, Java, etc.

Learning Guava – Calibrating time using Stopwatch

Many of our day-to-day applications would need calibrating time taken between 2 points. In Java world we either depend on System.currentTimeMillis() or System.nanoTime(). But the pain here is, we have to do the required computations of getting to a proper granularity to understand the time taken. Would n’t it be great it to have such an utility class which will give the required information in the granularity we need with minimum amount of boilerplate code?

Stopwatch is one such small and wonderful utility class in Guava which helps in calibrating elapsed time / duration between any 2 points in the logic. The advantage of using Guava’s Stopwatch is you can get the elapsed time in any measure i.e. right from nanoseconds to days. This is possible because you can pass an enum argument type of TimeUnit class to get the elapsed time in the desired granularity. Code snippet for the usage of the Stopwatch class:

Few caveats for using Stopwatch are you should not start an already started Stopwatch. One has to check if the Stopwatch is already running by invoking isRunning() method. Stopwatch documentation says the following on the same:
<blockquote class=”tr_bq” style=”background-color: white; box-sizing: border-box; color: #303030; font-size: 14px; line-height: 24px; margin-bottom: 15px;”>Stopwatch methods are not idempotent; it is an error to start or stop a stopwatch that is already in the desired state.</blockquote> Also, once I got burned down by StopWatch class of Apache Commons Lang. As I was working in an IDE on a Maven project, I could not quickly relate to the difference between Stopwatch of Guava and StopWatch of Apache Commons Lang, as the class got auto imported into the code and then spent some good 20 minutes trying to check my classpath, IDE setup, etc. Yes very silly mistake. So, please be careful in choosing the correct class.