how to measure method execution time in java

You can measure method execution time in java using the method System.nanoTime() or System.currentTimeMillis().

Put this method before and after the method or piece of code for which you want to measure the running time.

Find the difference of the time you got before and after your code. The difference is the running time.

Method Execution time Code Example:

In the main method, we have calculated the execution time in milliseconds for the method printMsg().

public class Sample {

	public static void main(String[] args) {
		// START TIME
		long start = System.currentTimeMillis();

		// YOUR METHOD
		printMsg();

		// END TIME
		long end = System.currentTimeMillis();

		// RUNNING TIME
		long runningTime = end - start;
		System.out.println("Running Time: " + runningTime);
	}

	public static void printMsg() {

		for (int i = 0; i < 1000; i++) {
			System.out
					.println("Mastering OOP as soon as I finish the Book: OOP Concepts Booster");
		}
	}
}

The output:

“Mastering OOP as soon as I finish the Book: OOP Concepts Booster” will be printed 1000 times with Running Time: 16 ( in milliseconds).

NOTE:

1)The running time will vary every time you run, depending on how much time the system is taking.

2)You can convert the time in milliseconds to seconds by dividing it by 1000.

Another method time measurement example

Here’s another example, where in a method I’ve demonstrated the running, or say elapsed time of a piece of code i.e., retrieving and printing an array element.

import java.util.ArrayList;
import java.util.List;

public class Sample {

	public static long getRunningTime(List arr) {
		// START TIME
		long start = System.currentTimeMillis();

		for (int i = 0; i < arr.size(); i++) {
			arr.get(i);
			System.out.println(i);
		}

		// END TIME
		long end = System.currentTimeMillis();

		// RUNNING TIME
		long runningTime = end - start;
		return runningTime;

	}

	public static void main(String[] args) {

		List arr = new ArrayList();

		int count = 1000;
		for (int i = 0; i < count; ++i) {
			arr.add(i);
		}
		System.out.println("Running Time: " + getRunningTime(arr));
	}
}

CONCLUSION:

Template to measure a method or a code section execution time in Java!

		// START TIME
		long start = System.currentTimeMillis();

		// YOUR METHOD CALL OR SECTION OF CODE GOES HERE
		

		// END TIME
		long end = System.currentTimeMillis();

		// RUNNING TIME
		long runningTime = end - start;		
		

Leave a Comment