ในบทความนี้ เราจะทำความเข้าใจวิธี วัดเวลาการทำงานของโปรแกรมหรือเมธอด (Execution Time) ใน Java โดยใช้ System.nanoTime()
หลักการ: บันทึกเวลาเริ่มต้น → รันโค้ด → บันทึกเวลาสิ้นสุด → ลบกันเพื่อหาเวลาที่ใช้ (นานวินาที/nanoseconds)
ตัวอย่าง Input และ Output
Input:
Run the program
Output:
The program is being executed: The Execution time of the program is: 620872 nanoseconds
อัลกอริธึม
ขั้นตอนที่ 1 - เริ่มต้น ขั้นตอนที่ 2 - ประกาศตัวแปร long 3 ตัว: my_start_time, my_end_time, my_execution_time ขั้นตอนที่ 3 - บันทึกเวลาเริ่มต้นด้วย System.nanoTime() ขั้นตอนที่ 4 - รันโค้ดที่ต้องการวัด ขั้นตอนที่ 5 - บันทึกเวลาสิ้นสุดด้วย System.nanoTime() ขั้นตอนที่ 6 - คำนวณ my_execution_time = my_end_time - my_start_time ขั้นตอนที่ 7 - แสดงผลลัพธ์ ขั้นตอนที่ 8 - หยุด
ตัวอย่างที่ 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");
}
}
Output
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");
}
}
Output
The program is being executed: The Execution time of the program is: 103801 nanoseconds