Java – how to measure time in Java efficiently

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * This program demonstrates how to measure time in Java efficiently.
 *
 * @author Bhavani P Polimetla
 * @since Feb-09-2011
 *
 */
public class TimeTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		// Test 1: Measure Time. (Can't measure methods which take very small
		// time in nano seconds.)
		long start = System.currentTimeMillis();
		workingHard();
		long end = System.currentTimeMillis();
		System.out.println("Test 1 Time==>" + (end - start) + " milli seconds");

		// Test 2: Measure Time. Date constructor uses
		// System.currentTimeMillis()
		// This is not good way
		start = (new Date()).getTime();
		workingHard();
		end = (new Date()).getTime();
		System.out.println("Test 2 Time==>" + (end - start) + " milli seconds");

		// Test 3: Measure Time in Nano seconds
		start = System.nanoTime();
		workingHard();
		end = System.nanoTime();
		System.out.println("Test 3 Time==>" + (end - start) + " nano seconds");

		// Conversion
		long duration = TimeUnit.NANOSECONDS.toMicros((end - start));
		System.out.println("Test 4 Time==>" + duration + " micro seconds");

	}

	public static void workingHard() {
		long k = 0;
		for (int i = 0; i < 1000; i++) { 			k = k + i; 		} 		System.out.println("I did big addition. : ) Final Total==>" + k);
	}

}

Result:
Test 1 Time==>0 milli seconds
I did big addition. : ) Final Total==>499500
Test 2 Time==>0 milli seconds
I did big addition. : ) Final Total==>499500
Test 3 Time==>462671 nano seconds
Test 4 Time==>462 micro seconds

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s