Java Stopwatch

In many cases, when programming, i want to measure the time some block of code has taken.

This functionality is needed in many projects I work on, and on each project it is sometimes needed many times.

The first few times i have done it manually, use getTimeInMillis() and deducted the end time from the starting time.

When it occurred several more times I have built a Stopwatch class, which is the path many have gone on before.

After tweaking that class several times, as my requirements became clearer to me, I have understood that I can do a decent job in the stopwatch class, but I can use a robust and maintained framework which has done a nicer job than mine, that was the stage where i went googling it out.

And i have found many classes implementing the stopwatch functionality, after narrowing them down, 3 frameworks remained:
1. Apache commons
2. Spring
3. Google's Guava

Which one did I pick?
What are the differences between them?

Basically they do the same things with slight changes.
Spring's - Has the nicest toString presentation but is very hard to find and download.
Apache's - Was the first big framework to implement it and is the smallest library (315kb)
Google's - Is the newest kid in town and has the most precision (it uses nano seconds), and has the option to return the time in any time unit needed. (it is 1.5mb though)

I couldn't find the spring library, so that went off the list.
I wanted the nano seconds precision and I am willing to pay with the added size of the library.

So I chose google's Guava library which was a good choice also because all of the cool java developers use the Guava libraries.


Michael Berkowitz said…
Thanks, Avi. I'm curious about the nano-second precision: Given the fact that code almost-always runs under a preemptive-multitasking OS, which plays hell with the timing of individual code events, it that kind of precision meaningful?
avi said…
I don't know.

I assume it is more accurate than just getting the milliseconds.

I can only quote the javadocs:

An object that measures elapsed time in nanoseconds. It is useful to measure elapsed time using this class instead of direct calls to System.nanoTime() for a few reasons:

An alternate time source can be substituted, for testing or performance reasons.
As documented by nanoTime, the value returned has no absolute meaning, and can only be interpreted as relative to another timestamp returned by nanoTime at a different time. Stopwatch is a more effective abstraction because it exposes only these relative values, not the absolute ones.
Basic usage:

Stopwatch stopwatch = new Stopwatch().start();
stopwatch.stop(); // optional

long millis = stopwatch.elapsedMillis();"that took: " + stopwatch); // formatted string like "12.3 ms"

Popular posts from this blog

Profiling Java @ 2019

Ant Explorer graphical Ant build tool

Shared/Pro/Managed Hosting for your site - which to choose ? (NO AFFILIATE LINKS!)