In this article, we will understand how to calculate the execution time of methods. Time of execution is calculated by substracting End time and start time.
Below is a demonstration of the same −
Input
Suppose our input is −
Run the program
Output
The desired output would be −
The program is being executed: The Execution time of the program is: 620872 nanoseconds
Algorithm
Step 1 - START Step 2 - Declare 3 long values namely my_start_time, my_end_time and my_execution_time. Step 3 - Start time of the program is recorded using the function System.nanoTime() and assigned to variable my_start_time. Step 4 - Similarly end time of the program is recorded using the function System.nanoTime() and assigned to variable my_end_time Step 5 - Total execution time of the program is calculated by my_end_time - my_start_time. Store the value in my_execution_time. Step 6 - Display the result Step 7 - Stop
Example 1
Here, the integer has been previously defined, and its value is accessed and displayed on the console.
public class Main { public static void main(String[] args) { long my_start_time, my_end_time, my_execution_time; my_start_time = System.nanoTime(); System.out.println("The program is being executed:"); my_end_time = System.nanoTime(); my_execution_time = my_end_time - my_start_time; System.out.println("The Execution time of the program is: " + my_execution_time + " nanoseconds"); } }
Output
The program is being executed: The Execution time of the program is: 129621 nanoseconds
Example 2
Here, the integer has been previously defined, and its value is accessed and displayed on the console.
public class Main { public static void main(String[] args) { long my_start_time, my_end_time, my_execution_time; my_start_time = System.nanoTime(); int my_input_1 = 100; int my_input_2 = 250; int my_sum = my_input_1 + my_input_2; System.out.println("The program is being executed:"); my_end_time = System.nanoTime(); my_execution_time = my_end_time - my_start_time; System.out.println("The Execution time of the program is: " + my_execution_time + " nanoseconds"); } }
Output
The program is being executed: The Execution time of the program is: 103801 nanoseconds