How to measure code execution time in Java


Being a Java Developer, if you often work on development of performance optimized code, then you may be required to calculate the execution time of certain code snippet.

There might be a number of reason for this such as…

  1. If you are debugging time critical methods in your code base.
  2. If you have 2 or more alternative way of writing a program but want to compare the speed of execution
  3. If you are calling an external library or API and want to measure the execution time of your API calls.

Let us explore how you can measure the execution time of certain code snippet in Java…

Java Image

We will use the method “System.nanoTime()” to record the current time in nano seconds.


Steps to measure the execution speed:
  1. Record the start time of execution in nano seconds.
  2. Execute the code snippet whose execution time is to be measured.
  3. Record the end time of execution in nano seconds.
  4. Calculate the difference between end time and start time. This becomes the execution time of the code snippet.

Let us try to understand this with an example

Let us suppose, we want to measure the execution speed of a simple “for loop”.

We will create a Java project and create a new Main method and write the below program inside the method:


    public static void main(String[] args) {
		long startTime = System.nanoTime();
		
		// Write your code snippet here or call your method here.
		// Sample code
		for (int i = 0; i < 100; i++) {
			System.out.println("The iteration count is:" + i);
		}
		
		long endTime = System.nanoTime();
		System.out.println("Time taken in nanoseconds:" + (endTime - startTime));

	} 

}

    

Upon running this program, the measured time taken in nano seconds will be displayed at the end of the program execution.

You can use this approach to measure different code snippets to compare the execution speed and to uncover any performance bottleneck in the program.

Follow Me on Social Media

Advertisement
FREE Sales CRM Software

Fully customizable CRM Software for Freelancers and Small Businesses

Signup for Free

Sign up for DigitalOcean Cloud

Get FREE $200 credits, deploy your hobby projects for Free

DigitalOcean Referral Badge
Sign up for Hostinger Cloud or VPS plans and get upto 20% Discount