*/rsh tech|
your source for programming know-how
Generated by:
Craftsman

The StopWatch

The StopWatch evolved way back in the early days of Java 1.1 and Java 1.2. It has been in use in RSH projects ever since. It is pretty much what its name implies: a stop watch for timing execution time.

Caveats

The execution time is obtained by recording the current time in milliseconds and then recording it again after the event is finished. The difference is the amount of time taken to execute the task being measured. This means that StopWatch can only record in increments of milliseconds (differences in nanoseconds show up as "0") and that StopWatch is dependendent on the VM for accuracy. If the VM in use or the platform it is running on has known time accuracy issues, this will directly affect the accuracy or results of the StopWatch.

Using StopWatch

Usage is fairly straight-forward:
StopWatch sw = new StopWatch();
sw.reset();
sw.start();
... // do something
sw.stop();
System.out.println(sw.getElapsed());
The operations start(), stop() and getElapsed() do pretty much what you expect. If you call getElapsed() without calling stop(), stop() is implicitly called for you.

The reset() operation resets all the counters, allowing you to re-use the same StopWatch over and over.

The HistoricalStopWatch

The HistoricalStopWatch is for recording several time periods and keeping track of all of them for later processing. For instance, you could perform several unit tests over and over again to test overhead. Instead of using the normal StopWatch, you use the HistoricalStopWatch and call next() each time you record one of your iterations. When finished executing all your iterations, you can retrieve all the times via getElapsedTimes(). It will return a List of Long objects. You can then manipulate this data using MathUtil to get information like the average time, the 90th percentile, etc.
HistoricalStopWatch sw = new HistoricalStopWatch();
sw.reset();
for (...) { // some loop of iterations to compare to one another
    sw.start();
    ... // do something
    sw.next();
}
System.out.println(MathUtil.getStandardDeviation(sw.getElapsedTimes()));

The StopWatchTree

The StopWatchTree allows you to "nest" StopWatches within one another, allowing you to get an idea of how long it takes to execute a series of tasks (that is, it gives you a break down of a stack of execution). This class is used primarily by the rsh-logging package's EventTracker. If you are trying to track execution times for your various functions, components, and applications, you should really look into EventTracker, as it will do all the work for you and even print it out in a nice format to your logging package of choice.