77. Implementing a stopwatch
A classical implementation for a stopwatch relies on System.nanoTime()
, System.currentTimeMillis()
, or on Instant.now()
. In all cases, we have to provide support for starting and stopping the stopwatch, and some helpers to obtain the measured time in different time units.
While the solutions based on Instant.now()
and currentTimeMillis()
are available in the bundled code, here we’ll show the one based on System.nanoTime()
:
public final class NanoStopwatch {
private long startTime;
private long stopTime;
private boolean running;
public void start() {
this.startTime = System.nanoTime();
this.running = true;
}
public void stop() {
this.stopTime = System.nanoTime();
this.running = false;
}
//elaspsed time in nanoseconds
public long getElapsedTime() {
if (running) {
return System.nanoTime() - startTime;
} else {
return stopTime - startTime;
}
}
}
If you need to return...