How To Measure Elapsed Execution Time In Java - Javarevisited

Javarevisited

Learn Java, Programming, Spring, Hibernate throw tutorials, examples, and interview questions

Topics and Categories

  • core java
  • spring
  • hibernate
  • collections
  • multithreading
  • design patterns
  • interview questions
  • coding
  • data structure
  • OOP
  • java 8
  • books
  • About Me
  • Java Certifications
  • JDBC
  • jsp-servlet
  • JSON
  • SQL
  • Linux
  • Courses
  • online resources
  • jvm-internals
  • REST
  • Eclipse
  • jQuery
  • Java IO
  • Java XML

Tuesday, July 27, 2021

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.

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. Other Java Programming tutorial you may like: Java Program to reverse String in Java using recursion Java Program to parse XML file using DOM parser Java Program to split String in Java using regular expression Java Program to convert Date to String in Java Java Program to check if number is prime or not Java Program to stop thread in Java Java Program to sort ArrayList in descending order in Java

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.

June 27, 2012 at 6:18 PM 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)

January 20, 2013 at 3:05 PM Unknown said...

import org.springframework.util.StopWatch;is not working in my ide..any solution for this problem!!!!!

February 17, 2013 at 7:07 AM

Post a Comment

Newer Post Older Post Home Subscribe to: Post Comments ( Atom )

Best System Design and Coding Interview Resources

System Design & Interview Prep

  • ByteByteGo Lifetime Plan (50% OFF)
  • Codemia Lifetime Plan (60% OFF)
  • Exponent Annual Plan (70% OFF)
  • Educative Premium Plus (55% OFF)
  • DesignGurus All Course Bundle (55% OFF)
  • Everything Java Interview Bundle (50% OFF)
  • 101 Blockchain (50% OFF)
  • Vlad Mihalcea's High Performance Bundle (50% OFF)
  • Javarevisited Substack Subscription (50% OFF)
  • Head First Software Architecture (Book)

Best Online Learning Resources and Platforms

  • Coursera Plus Discount (40% OFF)
  • Datacamp Discount (50% OFF)
  • AlgoMonster Discount (50% OFF)
  • Udemy Discount (80% OFF)
  • Baeldung Discount (33% OFF)
  • LabEx Discount (50% OFF)
  • Codecademy Discount (50% OFF)
  • Udacity Discount (50% OFF)
  • ZTM Academy Discount (20% OFF)
  • Frontend Masters Discount (10% OFF)
  • Whizlabs Discount (30% OFF)

Search This Blog

Preparing for Java and Spring Boot Interview?

  • Join My Newsletter .. Its FREE

My Books

  • Everything Bundle (Java + Spring Boot + SQL Interview) for a discount
  • Grokking the Java Interview
  • Grokking the Spring Boot Interview
  • Spring Framework Practice Questions
  • Grokking the SQL Interview
  • Grokking the Java Interview Part 2
  • Grokking the Java SE 17 Developer Certification (1Z0-829 Exam)

My Courses

  • Spring Professional Certification Practice Test
  • Java SE 11 Certification Practice Test
  • Azure Fundamentals AZ-900 Practice Test
  • Java EE Developer Exam Practice Test
  • Java Foundations 1Z0-811 Exam Practice Test
  • AWS Cloud Practitioner CLF-C02 Exam Practice Test
  • Java SE 17 1Z0-829 Exam Practice Test
  • Azure AI-900 Exam Practice Test
  • 1Z0-829 Java Certification Topic wise Practice Test

My Newsletter articles

  • How to grow financially as Software Engineer?
  • Difference between Microservices and Monolithic Architecture
  • What is Rate Limiter? How does it work
  • Difference between @Component vs @Bean annotations in Spring Framework?
  • Top 10 Software Design Concepts Every Developer should know
  • How does SSO Single Sign On Authentication Works?

Interview Questions

  • core java interview question (183)
  • interview questions (114)
  • data structure and algorithm (100)
  • Coding Interview Question (88)
  • spring interview questions (52)
  • design patterns (48)
  • object oriented programming (42)
  • SQL Interview Questions (37)
  • thread interview questions (30)
  • collections interview questions (26)
  • database interview questions (16)
  • servlet interview questions (15)
  • hibernate interview questions (11)
  • Programming interview question (6)

Java Tutorials

  • FIX protocol tutorial (16)
  • JDBC (35)
  • Java Certification OCPJP SCJP (33)
  • Java JSON tutorial (23)
  • Java Programming Tutorials (21)
  • Java multithreading Tutorials (64)
  • Java xml tutorial (16)
  • date and time tutorial (27)
  • java IO tutorial (30)
  • java collection tutorial (94)
  • jsp-servlet (37)
  • online resources (231)

Get New Blog Posts on Your Email

Get new posts by email:
Subscribe

Followers

Categories

  • courses (355)
  • SQL (80)
  • linux (54)
  • database (53)
  • Eclipse (38)
  • REST (34)
  • Java Certification OCPJP SCJP (33)
  • JVM Internals (27)
  • JQuery (26)
  • Testing (24)
  • Maven (16)
  • general (16)

Blog Archive

  • ▼  2021 (251)
    • ▼  July (101)
      • How to Solve UnrecognizedPropertyException: Unreco...
      • java.lang.ClassNotFoundException: org.postgresql.D...
      • Why multiple inheritances are not supported in Java
      • How to create HTTP Server in Java - ServerSocket E...
      • How to do GROUP BY in Java 8? Collectors.groupingB...
      • How SSL, HTTPS and Certificates Works in Java web ...
      • When to Make a Method Static in Java? Example
      • Different Types of JDBC Drivers in Java - Quick Ov...
      • Difference between ClassNotFoundException vs NoCla...
      • Why Enum Singleton are better in Java? Examples
      • 5 Coding Tips for Improving Performance of Java ap...
      • Difference between repaint and revalidate method i...
      • When a class is loaded and initialized in JVM - Ja...
      • Java ArrayList and HashMap Performance Improvement...
      • Is Swing Thread Safe in Java? Answer
      • Invalid initial and maximum heap size in JVM - How...
      • How to Close Java Program or Swing Application wit...
      • InvokeLater and InvokeAndWait in Java Swing (an ex...
      • How to Use Break, Continue, and Label in Loop in ...
      • 10 Examples of HotSpot JVM Options in Java
      • Difference between Sun (Oracle) JVM and IBM JVM?
      • How to Generate MD5 checksum for Files in Java? Ex...
      • How to find CPU and Memory used by Java process in...
      • How ClassLoader Works in Java? Example
      • How to use Comparator and Comparable in Java? With...
      • 10 Interview Questions on Java Generics for Progra...
      • What is -XX:+UseCompressedOops in 64 bit JVM? Example
      • Top 10 Garbage Collection Interview Questions and ...
      • What is Class File and Byte Code in Java? Example
      • Top 10 Java Swing Interview Questions Answers aske...
      • Difference between JVM, JIR, JRE, and JDK in Java?...
      • How to increase Heap memory of Apache Tomcat Serve...
      • How many characters allowed on VARCHAR(n) columns ...
      • What is bounded and unbounded wildcards in Generic...
      • Difference between Right shift and Unsigned right ...
      • What is the maximum Heap Size of 32 bit or 64-bit ...
      • How to Create JUnit Tests in Eclipse and NetBeans ...
      • How to add and substract days in current date in J...
      • 10 JDK 7 Features to Revisit, Before You Welcome J...
      • 7 Examples to Read File into a Byte Array in Java
      • How to Add Leading Zeros to Integers in Java ? Str...
      • How to Compare Two Enum in Java? Equals vs == vs C...
      • How to disable JUnit Test - @Ignore annotation Exa...
      • The Ultimate Guide of Generics in Java - Examples
      • Difference between trunk, tags and branches in SVN...
      • How to convert double to int in Java? Example
      • Does making all fields Final makes the class Immut...
      • Top 10 Tips on Logging in Java - Tutorial
      • How to Setup Java Remote Debugging in Eclipse - St...
      • Difference Between java and javaw Commands from JDK
      • Java Program to connect Oracle Database with Examp...
      • Difference between ValidatorForm vs ValidatorActio...
      • 10 points about Java Heap Space or Java Heap Memory
      • How to Measure Elapsed Execution Time in Java - Sp...
      • How to Invoke Method by Name in Java Dynamically U...
      • Difference Between java.util.Date and java.sql.Dat...
      • How to convert Local Time to GMT in Java - Example...
      • What is rt.jar in Java/JDK/JRE? Why it’s Important?
      • Java PropertyUtils Example - getting and setting p...
      • What is Effectively Final variable of Java 8? Example
      • Top 10 JSP Interview Questions Answers for Java Pr...
      • 5 Difference between Application Server and Web Se...
      • Display tag Pagination, Sorting Example in JSP and...
      • Bitwise and BitShift Operators in Java - AND, OR, ...
      • How to Install JDK on Windows - Java Programming...
      • How to format Date and Time in SQL Server and Syba...
      • What is JSESSIONID in Java Web application - JSP S...
      • How to Export HTML to PDF, CSV, and Excel using Di...
      • How to Configure HTTPS (SSL) in Tomcat 6 and 7 Jav...
      • JDBC - java.lang.ClassNotFoundException: com.mysql...
      • File Upload Example in Java using Servlet, JSP and...
      • How to Split String in JSP? JSTL forTokens Tag Exa...
      • How to test Exception thrown by a Java Method in J...
      • 10 examples of displaytag in JSP, Struts and Spring
      • How to change Tomcat default port 8080? Example Steps
      • How to define Error page in Java Web Application -...
      • How to Disable submit button in HTML JavaScript? M...
      • JSTL foreach tag example in JSP - looping ArrayList
      • JSP - How to check if ArrayList is Empty using JST...
      • Difference between Servlet and JSP? Example
      • How to get ServletContext in Servlet, JSP, Action ...
      • How to loop over HashMap in JSP using JSTL? Example
      • Difference Between ON HOLD and ON ICE Jobs in Auto...
      • How to find file and directory size in Unix with E...
      • Top 10 basic networking commands in linux/unix - E...
      • 10 Examples of CUT command in UNIX and Linux
      • Linux and UNIX Command Tutorial, Tips and Examples...
      • 10 xargs command example in Linux - Unix tutorial
      • 10 Examples of Date Command in Linux and UNIX
      • 5 Example of kill command in UNIX and Linux
      • 5 Articles to Learn about Shellshock Bash Bug
      • How to find IP Address from hostname in Windows Li...
      • 10 Examples of tar command in UNIX and Linux
      • List of special bash parameter used in Unix or Li...
      • 2 Ways to find Tomcat and Java Version in Linux an...
      • How to read a text file using Scanner in Java? Exa...
      • 4 Free OCAJP 7 and OCPJP7 Mock Exams - Online Prac...
      • Tibco Tutorials for Beginner to Learn RV and EMS
      • Difference between FIX 4.2 vs FIX 4.4 Protocol? An...
      • Basics of FIX protocol and FIX Engine - Examples

Contributors

  • SimpleJava
  • javin paul

Popular Posts

  • I found Leetcode for System Design and its Awesome credit- codemia.io Hello guys, If you’re preparing for  FAANG interviews , then you already know that  Data Structures & Algorithms (DSA...
  • I Joined 20+ Generative AI Online Courses — Here Are My Top 6 Recommendations for 2026 Hello guys, If you are following what's going on Tech then you may know that Generative AI has fundamentally changed the whole tech land...
  • How to create HTTP Server in Java - ServerSocket Example Java has very good networking support, allows you to write client-server applications by using TCP Sockets. In this tutorial, we will learn...
  • The 2025 Java Developer RoadMap [UPDATED] Hello guys, I have been sharing a lot of roadmaps to become a Web developer , DevOps engineer , and recently React.js developer . One of th...
  • I Tried ByteByteGo and LeetCode — Here’s the Better One for Interview Prep Hello guys, preparing for a technical interview in 2026 looks very different from what it did a few years ago. With companies increasingly e...
  • I Tested 30+ Websites to Learn Java: Here Are My Top 6 Recommendations for 2026 Hello guys, I’ve spent the last 48 months systematically testing and evaluating 30+ websites, courses, and platforms for learning Java. Not ...
  • Is ByteByteGo worth it in 2026 for System Design Interview Prep? Hello guys, when it comes to preparing for technical interviews, few challenges intimidate developers as much as system design .  While cod...
  • How HashMap works in Java? Hello guys, if you are looking for an answer of popular Java interview question, how HashMap works in Java? or How HashMap works internally ...
  • Top 133 Java Interview Questions Answers for 2 to 5 Years Experienced Programmers Time is changing and so is Java interviews. Gone are the days, when knowing the difference between String and StringBuffer can help you to g...
  • The 2026 Web Developer RoadMap Hello guys, if you want to learn to code or to become a Web Developer in 2026 then you have come to the right place. Earlier, I have shared ...

Subscribe To

Posts Atom Posts Comments Atom Comments

Pages

  • Privacy Policy
  • Terms & Conditions
Copyright by Javin Paul 2010-2025. Powered by Blogger.

Tag » How To Time Things In Java