HADOOP-14827. Allow StopWatch to accept a Timer parameter for tests. Contributed by Erik Krogen
(cherry picked from commit dd814946f68d52a9b1627ac4dd61f9ab093423ae)
This commit is contained in:
parent
2071f8338c
commit
c6db50503a
@ -25,11 +25,22 @@
|
|||||||
* A simplified StopWatch implementation which can measure times in nanoseconds.
|
* A simplified StopWatch implementation which can measure times in nanoseconds.
|
||||||
*/
|
*/
|
||||||
public class StopWatch implements Closeable {
|
public class StopWatch implements Closeable {
|
||||||
|
private final Timer timer;
|
||||||
private boolean isStarted;
|
private boolean isStarted;
|
||||||
private long startNanos;
|
private long startNanos;
|
||||||
private long currentElapsedNanos;
|
private long currentElapsedNanos;
|
||||||
|
|
||||||
public StopWatch() {
|
public StopWatch() {
|
||||||
|
this(new Timer());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Used for tests to be able to create a StopWatch which does not follow real
|
||||||
|
* time.
|
||||||
|
* @param timer The timer to base this StopWatch's timekeeping off of.
|
||||||
|
*/
|
||||||
|
public StopWatch(Timer timer) {
|
||||||
|
this.timer = timer;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -49,7 +60,7 @@ public StopWatch start() {
|
|||||||
throw new IllegalStateException("StopWatch is already running");
|
throw new IllegalStateException("StopWatch is already running");
|
||||||
}
|
}
|
||||||
isStarted = true;
|
isStarted = true;
|
||||||
startNanos = System.nanoTime();
|
startNanos = timer.monotonicNowNanos();
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -61,7 +72,7 @@ public StopWatch stop() {
|
|||||||
if (!isStarted) {
|
if (!isStarted) {
|
||||||
throw new IllegalStateException("StopWatch is already stopped");
|
throw new IllegalStateException("StopWatch is already stopped");
|
||||||
}
|
}
|
||||||
long now = System.nanoTime();
|
long now = timer.monotonicNowNanos();
|
||||||
isStarted = false;
|
isStarted = false;
|
||||||
currentElapsedNanos += now - startNanos;
|
currentElapsedNanos += now - startNanos;
|
||||||
return this;
|
return this;
|
||||||
@ -90,7 +101,7 @@ public long now(TimeUnit timeUnit) {
|
|||||||
*/
|
*/
|
||||||
public long now() {
|
public long now() {
|
||||||
return isStarted ?
|
return isStarted ?
|
||||||
System.nanoTime() - startNanos + currentElapsedNanos :
|
timer.monotonicNowNanos() - startNanos + currentElapsedNanos :
|
||||||
currentElapsedNanos;
|
currentElapsedNanos;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user