Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

메소드의 실행 시간을 계산하는 Java 프로그램

<시간/>

이 기사에서는 메소드의 실행 시간을 계산하는 방법을 이해할 것입니다. 실행 시간은 종료 시간과 시작 시간을 빼서 계산합니다.

아래는 동일한 데모입니다 -

입력

입력이 -

라고 가정합니다.
Run the program

출력

원하는 출력은 -

The program is being executed:
The Execution time of the program is: 620872 nanoseconds

알고리즘

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

예시 1

여기서 정수는 이전에 정의되었으며 그 값은 콘솔에 액세스되어 표시됩니다.

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");
   }
}

출력

The program is being executed:
The Execution time of the program is: 129621 nanoseconds

예시 2

여기서 정수는 이전에 정의되었으며 그 값은 콘솔에 액세스되어 표시됩니다.

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");
   }
}

출력

The program is being executed:
The Execution time of the program is: 103801 nanoseconds