Let's examine the following code:
long start = System.currentTimeMillis();
// some code to be measured
long stop = System.currentTimeMillis();
System.out.print(stop - start);
This is the usual way to measure how long it takes to execute a piece of code and it works just fine. But what if the code is executed may times. One would probably like to know how many times it was executed, what was the average time as well as minimum and maximum time taken to execute this code.
Is such case one can write some code to calculates all that (it is not that hard, after all) or simply use Stopwatch:
Stopwatch.setActive(true);
for (int count = 0; count < 21; count++) {
long id = Stopwatch.start("my group", "my label");
// some code to be measured
Stopwatch.stop(id);
}
Report report = Stopwatch.getSingleReport("my group", "my label");
System.out.print(report);
This will print sometning similar to :
Group="my group" Label="my label" Count=21 Min=12ms Avg=13ms Max=32ms Total=274ms
Another issue Stopwatch can resolve is ignoring "failed" executions. Let's say the performance of some code that can throw an exception is to be measured. If we are going to measure every single run and say half of them ends up with an exception thrown, the result can be very optimistic but most likely incorrect. So we only want to measure the "successful" executions and ignore the rest
Stopwatch.setActive(true);
for (int count = 0; count < 21; count++) {
long id = Stopwatch.start("my group", "my label");
try {
if (count % 5 == 0) throw new Exception();
// some code to be measured
} catch (Exception e) {
Stopwatch.skip(id);
} finally {
Stopwatch.stop(id);
}
}
Report report = Stopwatch.getSingleReport("my group", "my label");
System.out.print(report);
This will print sometning similar to :
Group="my group" Label="my label" Count=16 Min=11ms Avg=12ms Max=14ms Total=194ms
Note that Count=16
. Four measurments (count in 5,10,15,20) were skipped.