Measure execution time in Java – Spring StopWatch Example

There are two ways to measure elapsed execution time in Java either by using System.currentTimeinMillis() or by using System.nanoTime() . These two methods can be used to measure elapsed or execution time between two method calls or event in Java. Calculating elapsed time is one of the first thing Java programmer do to find out how many seconds or millisecond a method is taking to execute or how much time a particular code block is taking. Most of Java programmer are familiar with System.currentTimeInMillis() which is there from beginning while a new version of more precise time measurement utility System.nanoTime is introduced in Java 1.5, along with several new features in language like Generics, Enum types, auto boxing and variable arguments or varargs. You can use any of them to measure execution time of method in Java. Though its better to use System.nanoTime() for more precise measurement of time intervals.

Here is a code example for measuring elapsed time between two code blocks using System.nanoTime, M any open source Java libraries like Apache commons lang, Google commons and Spring also provides StopWatch utility class which can be used to measure elapsed time in Java. StopWatch improves readability to minimize calculation error while calculating elapsed execution time but beware that StopWatch is not thread safe and should not be shared in multi-threading environment and its documentation clearly says that this is more suitable in development and test environment for basic performance measurement rather performing time calculation in production environment.

import org.springframework.util.StopWatch;
/**
* Simple Java Program to measure elapsed execution time in Java
* This Java Program shows two ways for measuring time in Java, by using System.nanoTime() which was
* added in Java 5 and StopWatch which is a utility class from Spring Framework.
*/
public class MeasureTimeExampleJava {
public static void main(String args[]) {
//measuring elapsed time using System.nanoTime
long startTime = System.nanoTime();
for(int i=0; i < 1000000; i++){
Object obj = new Object();
}
long elapsedTime = System.nanoTime() - startTime;
System.out.println("Total execution time to create 1000K objects in Java in millis: "
+ elapsedTime/1000000);
//measuring elapsed time using Spring StopWatch
StopWatch watch = new StopWatch();
watch.start();
for(int i=0; i < 1000000; i++){
Object obj = new Object();
}
watch.stop();
System.out.println("Total execution time to create 1000K objects in Java using StopWatch in millis: "
+ watch.getTotalTimeMillis());
}
}
Output:
Total execution time to create 1000K objects in Java in millis: 18
Total execution time to create 1000K objects in Java using StopWatch in millis: 15

Which one should you use for measuring execution time in Java

It depends which options are available to you, if you are working in below JDK 1.5 version than System.currentTimeInMillis() is the best option in terms of availability while after JDK 1.5 System.nanoTime is great for measuring elapsed time as it is more accurate and uses accurate system clock and can measure upto nano second precision. while if you are using any of Java open source library mentioned above, mostly Spring than StopWatch is also a better option but as I said earlier StopWatch is not thread-safe and should only be used in development and test environment. Just like SimpleDateFormat is not thread-safe and you can use ThreadLocal to create per thread SimpleDateFormat you can do the same thing with StopWatch as well. But I don’t think StopWatch is heavy object like SimpleDateFormat .

That’s all on how to measure elapsed time or execution time in Java. Get yourself in habit of measuring performance and execution time of important piece of codes specially methods or loops which executes most of the time. Those are the places where an small optimization in code result in bigger performance gain.

and many more ....

3 comments

‘Cannot instantiate the type StopWatch’ was received at the code ‘StopWatch stopWatch = new StopWatch();’ Isn’t StopWatch a interface ? How do I get around this error? Thanks, I appreciate the tutorial.

Career Opportunities

Newsletter

Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

Email address:

Receive Java & Developer job alerts in your Area from our partners over at ZipRecruiter

Leave this field empty if you're human:

Join Us

With 1,240,600 monthly unique visitors and over 500 authors we are placed among the top Java related sites around. Constantly being on the lookout for partners; we encourage you to join us. So If you have a blog with unique and interesting content then you should check out our JCG partners program. You can also be a guest writer for Java Code Geeks and hone your writing skills!

Disclaimer

All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners. Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries. Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.