Monday 12 November 2012

A Timer class in Java

Have you ever wanted to time how long it takes to execute a particular section of your code?

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
 Those dot points look like methods to me. Lets write the code:


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