Sometimes we execute some code and care about how long it took, as we might want to store or log that duration. The use of

long start = System.currentTimeMillis();
doSomething();
long durationMs = System.currentTimeMillis() - start;
log.info("time: " + durationMs); // formatted string like "12.3 ms"

looks appealing at first, but for my taste it lacks intention or a higher-level concept of what we try to achieve here. It is quite low level in between our code, and can easily be implemented wrong.

An alternative can be Guava’s Stopwatch.

Here is how you would use it:

/* guava, com.google.common.base.Stopwatch */
Stopwatch stopwatch = Stopwatch.createStarted();
doSomething();
stopwatch.stop(); // optional

long millis = stopwatch.elapsed(MILLISECONDS);

log.info("time: " + stopwatch); // formatted string like "12.3 ms"

Please note that there are also others, for example in Spring framework.