72 lines
1.4 KiB
Java
72 lines
1.4 KiB
Java
package de.nclazz.commons;
|
|
|
|
import lombok.NonNull;
|
|
|
|
import java.time.Clock;
|
|
import java.util.function.LongConsumer;
|
|
import java.util.function.Supplier;
|
|
|
|
public class StopWatch {
|
|
|
|
private final Clock clock;
|
|
private long tStart;
|
|
private long tEnd;
|
|
private long finalTime = -1;
|
|
|
|
private LongConsumer elapsedTimeConsumer;
|
|
|
|
|
|
private StopWatch(Clock clock) {
|
|
this.clock = clock;
|
|
}
|
|
|
|
public StopWatch onCompleted(LongConsumer consumer) {
|
|
this.elapsedTimeConsumer = consumer;
|
|
return this;
|
|
}
|
|
|
|
public long getTimeStart() {
|
|
return this.tStart;
|
|
}
|
|
|
|
public long getTimeEnd() {
|
|
return this.tEnd;
|
|
}
|
|
|
|
public long getElapsedTime() {
|
|
return this.finalTime;
|
|
}
|
|
|
|
public <T> T measure(Supplier<T> supplier) {
|
|
this.tStart = this.clock.millis();
|
|
|
|
T result = supplier.get();
|
|
|
|
this.tEnd = this.clock.millis();
|
|
this.finalTime = this.tEnd - this.tStart;
|
|
|
|
return result;
|
|
}
|
|
|
|
public void measure(Runnable runnable) {
|
|
measure(emptySupplier(runnable));
|
|
}
|
|
|
|
private Supplier<Void> emptySupplier(Runnable runnable) {
|
|
return () -> {
|
|
runnable.run();
|
|
return null;
|
|
};
|
|
}
|
|
|
|
public static StopWatch defaultTimer() {
|
|
return new StopWatch(Clock.systemDefaultZone());
|
|
}
|
|
|
|
public static StopWatch forClock(@NonNull Clock clock) {
|
|
return new StopWatch(clock);
|
|
}
|
|
|
|
|
|
}
|