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 :
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 making a donation to this charity, thanks.

Related Posts

Popular Posts