เปรียบเทียบประสิทธิภาพของอัลกอริทึมการค้นหา
ในฐานะนักพัฒนาซอฟต์แวร์ของบริษัท e-commerce คุณกำลังประเมินวิธีการค้นหาต่าง ๆ เพื่อปรับปรุงฟีเจอร์ค้นหาสินค้า ที่ผ่านมาวิธีการค้นหาที่บริษัทใช้อยู่นั้นช้ามาก แต่คุณแก้ไขปัญหาดีเลย์ไปเรียบร้อยแล้ว ภารกิจตอนนี้คือเปรียบเทียบวิธีค้นหาใหม่กับวิธีเก่า เพื่อพิสูจน์ว่าวิธีใหม่มีประสิทธิภาพสูงกว่าสำหรับฟีเจอร์ค้นหาแคตตาล็อกสินค้า
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
การปรับแต่งโค้ดใน Java
คำแนะนำการฝึกหัด
- ค้นหาองค์ประกอบเป้าหมายโดยใช้วิธีใหม่
linearSearch() - จากนั้นค้นหาองค์ประกอบเดิมโดยใช้วิธีเก่า
linearSearchWithDelay() - คำนวณความแตกต่างด้านประสิทธิภาพเชิงเปรียบเทียบระหว่างทั้งสองวิธี
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
public class SearchPerformanceTest {
public static void main(String[] args) {
int[] array = new int[10000];
for (int i = 0; i < array.length; i++) {
array[i] = i;
}
int target = array[7500]; // Target value to search for
long startRegular = System.nanoTime();
// Do a search using the new search method
boolean foundRegular = ____(array, target);
long endRegular = System.nanoTime();
long startDelay = System.nanoTime();
// Do a search using the old search method
boolean foundDelay = ____(array, target);
long endDelay = System.nanoTime();
// Calculate the ratio between the old and new methods
double ratio = (double)(endDelay - startDelay) / (____ - ____);
System.out.println("Linear search with delay is " + ratio +
" times slower than regular linear search");
}
private static boolean linearSearch(int[] data, int target) {
for (int i = 0; i < data.length; i++) {
if (data[i] == target) return true;
}
return false;
}
private static boolean linearSearchWithDelay(int[] data, int target) {
for (int i = 0; i < data.length; i++) {
try {
Thread.sleep(0, 1000); // 1000 nanoseconds delay
} catch (InterruptedException e) {
e.printStackTrace();
}
if (data[i] == target) return true;
}
return false;
}
}