Program to calculate execution time of code/ functional block in java

  • Given the code or functional block of program , we would like to find elapsed time, to execute the code block.
  • We can find the execution time in milliseconds.  We can also find the execution time in nano seconds (if we need more precision).
    • Note down current clock time (milliseconds or nanoseconds)
      • Mark it as startTime
    • Execute the block of code
      • Whose execution time, we would like to measure
    • Note down the time at end of code block (milliseconds or nanoseconds)
      • Mark it as endTime
    • Find out the difference = endTime – startTime
      • We got the desired execution time

Program – calculate execution time of code/ functional block in java.

package org.learn;

class Employee {
	public String name;
	public int age;

	public Employee(String name, int age) {
		this.name = name;
		this.age = age;
	}

	public String toString() {
		return "[User: " + name + " " + age +  "]";
	}
}

public class ExecutionTime {	

	public static void main(String[] args) throws InterruptedException {
		//Example 1 : Time to 1000 create object using mills
		long startTime = System.currentTimeMillis();
		for (int index = 0 ; index < 1000; index++) {
			new Employee("name "+index,index);			
			Thread.sleep(10);
		}
		long endTime = System.currentTimeMillis();
		System.out.printf("1. Execution time to create 1000 objects: %d ms\n" ,
									(endTime-startTime));
		
		//Example 2 using nano second 
		startTime = System.nanoTime();
		for (int index = 0 ; index < 1000; index++) {
			new Employee("name "+index,index);			
			Thread.sleep(10);
		}
		endTime = System.nanoTime();
		System.out.printf("2. Execution time to create 1000 objects: %d ns" ,
									(endTime-startTime));
	}
}

Output – find execution time of code/functional block in java

1. Execution time to create 1000 objects: 10221 ms
2. Execution time to create 1000 objects: 10219039717 ns
Scroll to Top