Tuesday, April 18, 2017

How to Measure Elapsed Execution Time in Java - Spring Framework's 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 events in Java. Calculating elapsed time is one of the first things 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 Java programmers are familiar with System.currentTimeInMillis()which is there from the 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 a language like Generics, Enum types, autoboxing and variable arguments or varargs.


You can use any of them to measure the execution time of the 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.

By the way, if you are new to Spring framework then I also suggest you join a comprehensive and up-to-date course to learn Spring in depth. If you need recommendations, I highly suggest you take a look at Spring Framework 5: Beginner to Guru, one of the comprehensive and hands-on course to learn modern Spring. It' also most up-to-date and covers Spring 5. 

It's also very affordable and you can buy in just $10 on Udemy sales which happen every now and then. 

Java Program example to measure execution time in Java

Java Program Example to measure execution time in JavaHere is a code example for measuring the elapsed time between two code blocks using the System.nanoTime, Many open-source Java libraries like Apache commons-lang, Google commons, and Spring also provide StopWatch utility class which can be used to measure elapsed time in Java

The 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 a 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 a 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 the accurate system clock and can measure up to nanosecond 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 the 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 a StopWatch is a 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 an important piece of codes especially methods or loops which execute most of the time. Those are the places where a small optimization in code result in a bigger performance gains.

Further Reading
Spring Framework 5: Beginner to Guru
The Complete Java MasterClass
Core Java, Volume II--Advanced Features
Spring Fundamentals

Other Java Programming tutorial you may like:

3 comments :

James Zhou said...

System.currentTimeMillis() was my first way of doing method profiling i.e. measuring execution time of method in Java. Though there were lot of free profiler available like Netbeans profiler, I still find magic of nanoTime and millisTime very powerful. If you suspect any method is performance bottleneck just measure how much time it take, you can even log your performance metrics in separate log file for offline analysis.

Unknown said...

There is realy a better way to use the *light weight* (simply) implementation [commons-lang3] (http://commons.apache.org/lang/api/org/apache/commons/lang3/time/StopWatch.html) with real less dependencies to other Java-Libs.

see [example](http://code.google.com/p/neo-commons/source/browse/trunk/samples-javka/src/samples/SamplesDateUtils.java?spec=svn266&r=266)

Unknown said...

import org.springframework.util.StopWatch;

is not working in my ide..
any solution for this problem!!!!!

Post a Comment