Blog Details

Measure execution time for a method

1. What is execution time?

The duration of running the method is the execution time [Figure below]. In Java, there are plenty of methods to measure the execution time.

2. Solutions

  • Use System.currentTimeMills() [find test1()]
  • Use System.nanoTime() [find test2()]
  • Use Java8 new feature Instant and Duration [find test3()]
public class ExcuteTime {
	@Test
	public void test1() {
		long startTime = System.currentTimeMillis();
		myMethod();
		long endTime = System.currentTimeMillis();
		double elapsedTime = (endTime - startTime) / 1000.0;
		System.out.println("The total elapsed time is " + elapsedTime + " seconds.");
	}
	
	@Test
	public void test2() {
		long startTime = System.nanoTime();
		myMethod();
		long endTime = System.nanoTime();
		double elapsedTime = (endTime - startTime)/1000000000.0;
		System.out.println("The total elapsed time is " + elapsedTime + " seconds.");
	}
	
	@Test
	public void test3() {
		Instant startInstant = Instant.now();
		myMethod();
		Instant endInstant = Instant.now();
		Duration elpsedTime = Duration.between(startInstant, endInstant);
		System.out.println("The total elapsed time is " + elpsedTime.toMillis() / 1000.0 + " seconds.");
	}
	
	public void myMethod() {
		long total = 0;
		for(long i = 0; i < 10000000; i ++) {
			total += i;
			total += i;
		}
	}
}

3. Results