Site icon

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

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
Exit mobile version