How To Measure Elapsed Execution Time In Java - Javarevisited
Maybe your like
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
Here 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 Labels: core java , spring3 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
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:
SubscribeFollowers
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
- ► 2026 (91)
- ► March (13)
- ► February (42)
- ► January (36)
- ► 2025 (910)
- ► December (23)
- ► November (33)
- ► October (121)
- ► September (39)
- ► August (20)
- ► July (111)
- ► June (106)
- ► May (85)
- ► April (116)
- ► March (32)
- ► February (105)
- ► January (119)
- ► 2024 (185)
- ► December (14)
- ► November (3)
- ► October (35)
- ► September (28)
- ► August (10)
- ► July (20)
- ► June (7)
- ► May (24)
- ► April (30)
- ► March (9)
- ► February (1)
- ► January (4)
- ► 2023 (511)
- ► December (4)
- ► November (4)
- ► October (7)
- ► September (149)
- ► August (20)
- ► July (43)
- ► June (2)
- ► May (151)
- ► April (91)
- ► March (27)
- ► February (8)
- ► January (5)
- ► 2022 (69)
- ► December (1)
- ► September (1)
- ► August (20)
- ► July (20)
- ► June (7)
- ► May (5)
- ► April (4)
- ► March (3)
- ► February (6)
- ► January (2)
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
Pages
- Privacy Policy
- Terms & Conditions
Tag » How To Time Things In Java
-
How Do I Time A Method's Execution In Java? - Stack Overflow
-
Measure Elapsed Time In Java - Baeldung
-
Measure Elapsed Time (or Execution Time) In Java - Techie Delight
-
How To Measure Execution Time For A Java Method? - Tutorialspoint
-
How Do I Time Things In Java? - Javamex
-
Here's How To Calculate Elapsed Time In Java - Stackify
-
How To Measure Time Taken By A Function In Java ? - GeeksforGeeks
-
How To Calculate Method Execution Time In Java | Edureka Community
-
LocalTime (Java Platform SE 8 ) - Oracle Help Center
-
Elegantly Log Elapsed Time In Java | By Hasan Alsulaiman
-
Java Program To Calculate The Execution Time Of Methods - Programiz
-
Java Program To Calculate Difference Between Two Time Periods
-
Working In Java Time - InfoWorld
-
Java Timer TimerTask Example - DigitalOcean