Java benchmark performance - A Stopwatch class for timings, benchmarks, and performance tuning

I think I found the Java Stopwatch class (shown below) in a book named Java Platform Performance. You can use the class for general performance timings, or make it part of an overall benchmarking system.

I take no credit for this Java code -- I didn't write it, and at the moment I can't find that book -- but I found it on my laptop, and wanted to make sure I have a copy of it laying around for when I need it.

/** 
 * Author unknown, but I think this is from a book
 * named "Java Platform Performance".
 */
public class Stopwatch {
  private long startTime = -1;
  private long stopTime = -1;
  private boolean running = false;

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

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

  public long getElapsedTime() {
    if (startTime == -1) {
      return 0;
    }
    if (running) {
      return System.currentTimeMillis() - startTime;
    }
    else {
      return stopTime - startTime;
    }
  }

  public Stopwatch reset() {
    startTime = -1;
    stopTime = -1;
    running = false;
    return this;
  }

  public static void main(String[] args)
  {
    Stopwatch s = new Stopwatch();
    s.start();
    // your code runs here
    s.stop();
    System.err.println("elapsed time: " + s.getElapsedTime());
  }
}
Permalink

You're right about the book this code comes from.
It can be found online : http://java.sun.com/docs/books/performance/1st_edition/html/JPMeasurement.fm.html

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.