Calculate elapsed time using Apache Commons Lang StopWatch

You need to calculate the timing or elapsed time of your code execution,

so you know how long a particular method or some block of code take to finish its execution. You can do this by capturing the start-time and the end-time using System.currentTimeMillis() and find their differences. Another way is to use the StopWatch class from the Apache Commons Lang library. The StopWatch class can be found in the org.apache.commons.lang3.time package.

The simplest steps to use the StopWatch is to create an instance of the StopWatch class, start the stopwatch by calling the start() method. After the stopwatch is started you can execute the target method or block of code you want to watch and call the stop() method to complete the timing session. To get the time of the stopwatch, you can call the getTime() method.

Now, let’s see the code for the process described above.

package org.kodejava.commons.lang;

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

public class StopWatchExample {
    public static void main(String[] args) {
        StopWatchExample demo = new StopWatchExample();
        demo.timingOne();
    }

    private void timingOne() {
        // Create an instance of StopWatch.
        StopWatch stopWatch = new StopWatch();

        // Start the watch, do some task and stop the watch.
        stopWatch.start();
        doSomeTask(5000);
        stopWatch.stop();

        // Print out the total time of the watch
        System.out.println("Time: " + stopWatch.getTime());
    }

    private void doSomeTask(long sleep) {
        try {
            Thread.sleep(sleep);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Here is the output of the code above:

Time: 5000

Besides doing a simple timing calculation using the start() and stop() followed by the getTime() methods, the StopWatch class also provides methods for splitting the time, suspend and resuming the stopwatch. You can use the split(), suspend() and resume() method respectively. To get the split time you can call the toSplitString() method.

package org.kodejava.commons.lang;

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

public class StopWatchAnotherExample {
    public static void main(String[] args) {
        StopWatchAnotherExample demo = new StopWatchAnotherExample();
        demo.timingTwo();
    }

    private void timingTwo() {
        // Create an instance of StopWatch and start the stopwatch.
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        // Do some task and split the stopwatch time.
        doSomeTask(3000);
        stopWatch.split();
        System.out.println("Split 1: " + stopWatch.toSplitString());

        // Suspend the stopwatch and resume the stopwatch.
        stopWatch.suspend();
        doSomeTask(4000);
        stopWatch.resume();

        // Do some task and split the stopwatch time.
        doSomeTask(2500);
        stopWatch.split();
        System.out.println("Split 2: " + stopWatch.toSplitString());

        // Do some task and split the stopwatch time.
        doSomeTask(1000);
        stopWatch.split();
        System.out.println("Split 3: " + stopWatch.toSplitString());

        // Stop the stopwatch and the total execution time.
        stopWatch.stop();
        System.out.println("Time: " + stopWatch.getTime());
    }

    private void doSomeTask(long sleep) {
        try {
            Thread.sleep(sleep);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

The code snippet above will output something like this:

Split 1: 00:00:03.004
Split 2: 00:00:05.518
Split 3: 00:00:06.522
Time: 6522

Another method that you can find in the StopWatch class is the getStartTime() which will return the stopwatch start time. The reset() method will reset the stopwatch. To remove a split, you can call the unsplit() method.

Maven Dependencies

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.14.0</version>
</dependency>

Maven Central

Wayan

4 Comments

    • The StopWatch class provides other functionality like:

      • You can start, stop and reset the StopWatch using start(), stop() and reset() methods.
      • You can also obtain the split time using the split() and unsplit() methods.
      • To pause and resume the StopWatch use the suspend(), resume() methods.

      You don’t have this default functionality when using the System.nanoTime() or the System.currentTimeMillis().

      Reply
    • Even you can get time in different time unit other than nanos. For example Stopwatch has getTime(TimeUnit timeUnit). You provide timeUnit’s SECONDS, MINUTES and etc and you get respective time.

      Beside this you can reset stopwatch using reset method. You can split time and get that split time. You can suspend stopwatch and then resume it if your logic demand it. It has resume(), suspend() method. So it is very handy.

      You can not find such handy facilities in System.currentTimeMillis. I mean measuring code execution timing is easy with Apache’s Stopwatch.

      Reply
  1. public class StopWatch extends Object

    StopWatch provides a convenient API for timings.

    To start the watch, call start() or createStarted(). At this point you can:

    split() the watch to get the time whilst the watch continues in the background. unsplit() will remove the effect of the split. At this point, these three options are available again.

    suspend() the watch to pause it. resume() allows the watch to continue. Any time between the suspend and resume will not be counted in the total. At this point, these three options are available again.

    stop() the watch to complete the timing session.

    It is intended that the output methods toString() and getTime() should only be called after stop, split or suspend, however a suitable result will be returned at other points.

    NOTE: As from v2.1, the methods protect against inappropriate calls. Thus you cannot now call stop before start, resume before suspend or unsplit before split.

    split(), suspend(), or stop() cannot be invoked twice.
    unsplit() may only be called if the watch has been split()
    resume() may only be called if the watch has been suspend()
    start() cannot be called twice without calling reset()

    Reference From:
    https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/time/StopWatch.html

    Reply

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.