A tiny timer implementation in Java

There exist very sophisticated timer libraries for Java around. Most of the time, however, I only need a tiny class which essentially caches a start and end point in time, and that’s it – such as the following:

public class Timer
{
  private long startTime;
  private long endTime;

  public void start()
  {
      this.startTime = System.currentTimeMillis();
  }

  public void stop()
  {
      this.endTime = System.currentTimeMillis();
  }

  public long getTimeInMillis()
  {
      return this.endTime - this.startTime;
  }

  public double getTimeInSeconds()
  {
      return this.getTimeInMillis() / 1000.0;
  }
}

Leave a Reply