Created
March 20, 2017 16:22
-
-
Save monkstone/e848b58d9df93b587b0095ec5b469e0b to your computer and use it in GitHub Desktop.
Stop watch using System.nano
This file contains hidden or 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
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