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.