Created
May 8, 2012 07:07
-
-
Save twaddington/2633213 to your computer and use it in GitHub Desktop.
Simple Java Timer class.
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 com.geoloqi.android.sdk.util; | |
import java.util.concurrent.TimeUnit; | |
/** | |
* A simple class for timing short lived events. | |
* | |
* @author Tristan Waddington | |
*/ | |
public class Timer { | |
private long mStart = 0; | |
private long mEnd = 0; | |
private boolean mRunning = true; | |
private Timer(long now) { | |
mStart = now; | |
} | |
@Override | |
public String toString() { | |
return getElapsedString(TimeUnit.SECONDS); | |
} | |
/** | |
* Get the elapsed runtime in nanoseconds. | |
* @return the runtime in nanoseconds. | |
*/ | |
public long getElapsed() { | |
if (mRunning) { | |
return System.nanoTime() - mStart; | |
} | |
return mEnd - mStart; | |
} | |
/** | |
* Get the elapsed runtime in {@link TimeUnit}. | |
* | |
* @param unit the desired unit. | |
* @return the elapsed runtime converted from nanoseconds to the requested TimeUnit. | |
*/ | |
public double getElapsed(TimeUnit unit) { | |
double elapsed = -1; | |
switch(unit) { | |
case SECONDS: | |
elapsed = (double) getElapsed() / 1000000000.0; | |
break; | |
case MILLISECONDS: | |
elapsed = (double) getElapsed() / 1000000.0; | |
break; | |
case NANOSECONDS: | |
elapsed = getElapsed(); | |
break; | |
} | |
return elapsed; | |
} | |
/** Stub */ | |
public String getElapsedString(TimeUnit unit) { | |
String u = ""; | |
switch(unit) { | |
case SECONDS: | |
u = "s"; | |
break; | |
case MILLISECONDS: | |
u = "ms"; | |
break; | |
case NANOSECONDS: | |
u = "ns"; | |
break; | |
} | |
return String.format("%s%s", getElapsed(unit), u); | |
} | |
/** | |
* Stop the timer and return the elapsed runtime in nanoseconds. | |
* @return the Timer object so methods can be chained. | |
*/ | |
public Timer end() { | |
if (mRunning) { | |
mEnd = System.nanoTime(); | |
mRunning = false; | |
} | |
return this; | |
} | |
/** | |
* Start a new {@link Timer}. | |
* @return a new Timer object. | |
*/ | |
public static Timer start() { | |
return new Timer(System.nanoTime()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment