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…
Let us explore how you can measure the execution time of certain code snippet in Java…
We will use the method “System.nanoTime()” to record the current time in nano seconds.
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.
Fully customizable CRM Software for Freelancers and Small Businesses