Is there a stopwatch in Java?

user1007522 picture user1007522 · Nov 24, 2011 · Viewed 219.2k times · Source

Is there a stopwatch in Java? On google I only find code of stopwatches which don't work - they always return 0 milliseconds.

This code that I found doesn't work but I don't see why.

public class StopWatch {

  private long startTime = 0;
  private long stopTime = 0;
  private boolean running = false;


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


  public void stop() {
    this.stopTime = System.currentTimeMillis();
    this.running = false;
  }


  //elaspsed time in milliseconds
  public long getElapsedTime() {
    long elapsed;
    if (running) {
      elapsed = (System.currentTimeMillis() - startTime);
    } else {
      elapsed = (stopTime - startTime);
    }
    return elapsed;
  }


  //elaspsed time in seconds
  public long getElapsedTimeSecs() {
    long elapsed;
    if (running) {
      elapsed = ((System.currentTimeMillis() - startTime) / 1000);
    } else {
      elapsed = ((stopTime - startTime) / 1000);
    }
    return elapsed;
  }
}

Answer

Lukas Eder picture Lukas Eder · Nov 24, 2011

You'll find one in

http://commons.apache.org/lang/

It's called

org.apache.commons.lang.time.StopWatch

But it roughly does the same as yours. If you're in for more precision, use

System.nanoTime()

See also this question here:

Time measuring overhead in Java