How to calculate elapsed / execute time in Java

This example show you 3 ways to calculate the program elapsed / execution time in milliseconds.

1. Date().getTime()

	long lStartTime = new Date().getTime();
	//some tasks
	long lEndTime = new Date().getTime();
 
	long difference = lEndTime - lStartTime;
 
	System.out.println("Elapsed milliseconds: " + difference);

2. System.currentTimeMillis()

	long lStartTime = System.currentTimeMillis();
	//some tasks
	long lEndTime = System.currentTimeMillis();
 
	long difference = lEndTime - lStartTime;
 
	System.out.println("Elapsed milliseconds: " + difference);

3. System.nanoTime()

	long lStartTime = System.nanoTime();
	//some tasks
	long lEndTime = System.nanoTime();
 
	long difference = lEndTime - lStartTime;
 
	System.out.println("Elapsed milliseconds: " + difference/1000000);

Full Example

package com.mkyong.time
 
import java.util.Date;
 
public class TimeApp {
	public static void main(String[] argv) {
 
		long lStartTime = new Date().getTime(); // start time
 
		createArray(); // some tasks to eat time
 
		long lEndTime = new Date().getTime(); // end time
 
		long difference = lEndTime - lStartTime; // check different
 
		System.out.println("Elapsed milliseconds: " + difference);
 
	}
 
	public static void createArray() {
 
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
 
		String sArray[] = new String[1000000];
 
		for (int i = 0; i < 1000000; i++)
			sArray[i] = "Array " + i;
 
	}
}

Output

Elapsed milliseconds: 2379

References

  1. System.nanoTime() JavaDoc
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

  • Pingback: Java – Time elapsed in days, hours, minutes, seconds()

  • http://bukanpenggunawindows.blogspot.com Ade Malsasa Akbar

    But how if i wanna count total minutes from two different time? Times are start hour:minute and end hour:minute? Please give an answer copy to my blog. Thank you…

  • Anonymosu

    You can also use StopWatch class from Spring to calculate time difference as shown in this article.

  • mydhinda

    Expected java would have something in built.
    But this is a good approach too !
    Thanks for sharing.

  • Kouassi

    What is the time equivalent in Swiss if CET time is reading at 2:30pm ?

    How do we calculate other time difference from java?