Java makes it easy to create a simple class to achieve this.
We want the following things:
- Tell the timer when to start counting
- Tell the timer when to stop counting
- Give us the time elapsed
public class Timer
{
private long mInitialTime;
private long mFinalTime;
public Timer()
{
start();
}
public void start()
{
mInitialTime = System.currentTimeMillis();
mFinalTime = mInitialTime;
}
public String end(String description)
{
mFinalTime = System.currentTimeMillis() - mInitialTime;
return description + ": total time " + getTimeElapsed();
}
public long getTimeElapsed()
{
return mFinalTime;
}
}
The timer will start either on object construction or on calling start()
The timer will end when you call end(String) and return a convenient description of how long it took.
If you want the time elapsed in long form, use getTimeElapsed()
Simple as that. :)
No comments:
Post a Comment