Skip to content

Instantly share code, notes, and snippets.

@monkstone
Created March 20, 2017 16:22
Show Gist options
  • Save monkstone/e848b58d9df93b587b0095ec5b469e0b to your computer and use it in GitHub Desktop.
Save monkstone/e848b58d9df93b587b0095ec5b469e0b to your computer and use it in GitHub Desktop.
Stop watch using System.nano
package monkstone;
public class StopWatch {
private long startTime, pausedTime;
private boolean paused = true;
public StopWatch() {
startTime = System.nanoTime();
}
public StopWatch start() {
startTime = System.nanoTime() - pausedTime;
paused = false;
return this;
}
public long time() {
return paused ? pausedTime : System.nanoTime() - startTime;
}
public int millis() {
return (int) (time() / 1_000_000);
}
public int second() {
return (int) (time() / 1_000_000 / 60);
}
/**
* @return Returns the current no of minutes as per the stopwatch
*/
public int minute() {
return (int) (time() / 60_000_000 / 60);
}
public int hour() {
return (int) (time() / 3_600_000_000L);
}
public void pause() {
pausedTime = System.nanoTime() - startTime;
paused = true;
}
@Override
public String toString() {
return "start: " + startTime + ", pausedTime: " + pausedTime + ", paused: " + paused;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment