Last active
August 13, 2018 10:13
-
-
Save Crydust/fa83f4eda1111d95e2501bf27a4d3994 to your computer and use it in GitHub Desktop.
Simple chronometer in java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.concurrent.TimeUnit; | |
public class Chronometer implements Comparable<Chronometer> { | |
boolean started = false; | |
boolean stopped = false; | |
long start; | |
long end; | |
public void start() { | |
started = true; | |
start = System.nanoTime(); | |
} | |
public void stop() { | |
if (!started) { | |
throw new IllegalStateException("Can't stop before start"); | |
} | |
stopped = true; | |
end = System.nanoTime(); | |
} | |
public long getNanos() { | |
if (!started) { | |
throw new IllegalStateException("Can't calculate time before being started and stopped"); | |
} | |
if (!stopped) { | |
throw new IllegalStateException("Can't calculate time before being stopped"); | |
} | |
return end - start; | |
} | |
public long getMillis() { | |
return TimeUnit.NANOSECONDS.toMillis(getNanos()); | |
} | |
@Override | |
public String toString() { | |
return getMillis() + " ms"; | |
} | |
public boolean lt(Chronometer o) { | |
return compareTo(o) < 0; | |
} | |
public boolean le(Chronometer o) { | |
return compareTo(o) <= 0; | |
} | |
public boolean gt(Chronometer o) { | |
return compareTo(o) > 0; | |
} | |
public boolean ge(Chronometer o) { | |
return compareTo(o) >= 0; | |
} | |
@Override | |
public int compareTo(Chronometer o) { | |
return Long.compare(getNanos(), o.getNanos()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment