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>
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024
Is there any advantage in using stopwatch compared to System.nanotime or milliseconds methods?
The
StopWatch
class provides other functionality like:StopWatch
usingstart()
,stop()
andreset()
methods.split()
andunsplit()
methods.StopWatch
use thesuspend()
,resume()
methods.You don’t have this default functionality when using the
System.nanoTime()
or theSystem.currentTimeMillis()
.Even you can get time in different time unit other than nanos. For example
Stopwatch
hasgetTime(TimeUnit timeUnit)
. You providetimeUnit
’sSECONDS
,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.public class StopWatch extends Object
StopWatch provides a convenient API for timings.
To start the watch, call
start()
orcreateStarted()
. 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()
andgetTime()
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()
, orstop()
cannot be invoked twice.unsplit()
may only be called if the watch has beensplit()
resume()
may only be called if the watch has beensuspend()
start()
cannot be called twice without callingreset()
Reference From:
https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/time/StopWatch.html