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

I think I found the Java Stopwatch class (shown below) many years ago 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();
    // your code runs here
    System.err.println("elapsed time: " + s.getElapsedTime());



You're right about the book this code comes from.
It can be found online :

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.