Java StopWatch: Calculating Execution Time

A stopwatch is a handy tool for measuring the execution time of methods, thus helping us track the elapsed time taken in parts of request processing. In this article, we’ll explore how to create a simple stopwatch in Java.

1. Implementing a Custom StopWatch in Java 8

Since Java 8, we use java.time.Instant class to capture the current time with nanosecond precision. To calculate the execution time of program operations, we can capture the current time before the program execution begins and after the program execution ends.

By knowing the difference between start and end time, we can calculate the program execution time.

Stopwatch stopwatch = new Stopwatch();
stopwatch.start();

// ...

stopwatch.stop();

long millis = stopwatch.getElapsedTime();
long nanos = stopwatch.getElapsedTime(TimeUnit.NANOSECONDS);

To implement the custom stopwatch, we have created a class Stopwatch which records its start time and end time when we invoke the start() and stop() methods. If we do not invoke the stop() method, it returns the time elapsed since we called the start() method.

public final class Stopwatch {

  private Instant startTime;
  private Instant endTime;
  private boolean running;

  public void start() {
    if (!running) {
      startTime = Instant.now();
      running = true;
    } else {
      System.out.println("Stopwatch is already running. Use stop() before starting again.");
    }
  }

  public void stop() {
    if (running) {
      endTime = Instant.now();
      running = false;
    } else {
      System.out.println("Stopwatch is not running. Use start() before stopping.");
    }
  }

  public Duration getElapsedDuration() {
    if (running) {
      return Duration.between(startTime, Instant.now());
    } else {
      return Duration.between(startTime, endTime);
    }
  }

  public long getElapsedTime() {
    Duration duration = getElapsedDuration();
    return duration.toMillis();
  }

  public long getElapsedTime(TimeUnit timeUnit) {
    return timeUnit.convert(getElapsedTime(), TimeUnit.MILLISECONDS);
  }
}

2. Apache Common’s StopWatch

Apache Commons Lang3 library provides a built-in implementation of org.apache.commons.lang3.time.StopWatch class that we can use directly in the code. The usage pattern is similar to the way we have discussed for the custom stopwatch.

import org.apache.commons.lang3.time.StopWatch;

//...

Stopwatch stopwatch = new Stopwatch();
stopwatch.start();

// ...

stopwatch.stop();
long millis = stopwatch.getElapsedTime();
long nanos = stopwatch.getElapsedTime(TimeUnit.NANOSECONDS);

This StopWatch provides additional functionalities such as:

  • It can be paused and resumed using suspend() and resume() methods so the same stopwatch instance can be used to calculate execution time in different parts of the code. Any time between the suspend and resume will not be counted in the total.
  • It can created in started mode with its createStarted() method. This way, we do not need to call the start() method explicitly.
  • Its split() method helps the watch to get the time whilst the watch continues in the background. The unsplit() will remove the effect of the split.
  • It forces the method calls in the appropriate order, thus you cannot now call stop before start, resume before suspend, or unsplit before split.

But note that this stopwatch is not thread-safe.

3. Conclusion

This short Java tutorial discussed how to implement and use a StopWatch functionality in Java. We created a custom bare minimum implementation of StopWatch for simple usecases. For advanced usecases, we should be using the Apache Commons StopWatch class.

Happy Learning !!

Source Code on Github

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode