Skip to content

Instantly share code, notes, and snippets.

@vegaasen
Created September 8, 2014 08:33
Show Gist options
  • Select an option

  • Save vegaasen/53d761e2312f71fa19dc to your computer and use it in GitHub Desktop.

Select an option

Save vegaasen/53d761e2312f71fa19dc to your computer and use it in GitHub Desktop.
StopWatch - simple stopwatch-thingie
import java.util.Date;
import java.util.concurrent.TimeUnit;
/**
* Simple Stopwatch implementation in order to measure ..things.
*
* @author <a href="mailto:[email protected]">Vegard Aasen</a>
* @since 8:30 PM
*/
public final class StopWatch {
private long start = 0L;
private long stop = 0L;
private boolean running = false;
private String watchName = "Casio Stopwatch";
public StopWatch() {
}
public void start() {
start = System.currentTimeMillis();
running = true;
}
public void stop() {
stop = System.currentTimeMillis();
running = false;
}
public void reset() {
start = 0L;
stop = 0L;
running = false;
}
public long elapsedTime(final TimeUnit unit) {
final TimeUnit u = TimeUnit.MILLISECONDS;
return u.convert(elapsedTime(), unit);
}
public boolean isActive() {
return running;
}
public long elapsedTime() {
if (start > 0L && running) {
return System.currentTimeMillis() - start;
} else if (start > 0L && !running) {
return stop - start;
}
return 0L;
}
public long getTotalTimeMillis() {
if (start > 0L && stop > 0L) {
return stop - start;
}
throw new IllegalStateException("Either stop or start have not yet been triggered. Take care of that first.");
}
public Date getStarted() {
if (start > 0) {
return new Date(start);
}
return null;
}
public Date getStopped() {
if (isActive()) {
throw new IllegalStateException("Stopwatch is still running.");
}
if (stop > 0) {
return new Date(stop);
}
return null;
}
public String getWatchName() {
return watchName;
}
public void setWatchName(final String name) {
watchName = name;
}
@Override
public String toString() {
return String.format("%s started running %s, and completed %s. Time so far %sms.",
getWatchName(),
(start > 0) ? new Date().toString() : "**Not started yet**",
(stop > 0) ? new Date().toString() : "**Still active**",
isActive() ? elapsedTime() : getTotalTimeMillis());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment