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.
In this Java programming tutorial we will see a simple Java program to measure execution time by using System.nanoTime() and Spring framework’s StopWatch utility class. This article is in continuation of my post on covering fundamental Java concepts like How to compare String in Java, How to write equals method in Java correctly and 4 ways to loop HashMap in Java. If you haven’t read them already you may find them useful. 

Java Program example to measure execution time in Java 

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. 

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

3 Responses to "Measure execution time in Java – Spring StopWatch Example"

  1. Joe Maldonado says:

    ‘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.

  2. Joe Maldonado says:

    Thanks. I figured it out. Sorry.

  3. shyam says:

    How to execute thread execution time and how to specify the thread execution time?

Leave a Reply


three − 3 =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
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.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close