在平时的开发学习过程中,我们可能需要计算某个函数(或者某段代码)的运行时间,并比较它们的速度。
这时候我们会用到nanoTime,但是重复写这段代码显得很复杂臃肿,所以我把它封装成了一个函数,用于计算另一个函数的运行时间。
以二分遍历binarySearch和顺序遍历sequentialSearch为例:
package main; import java.util.*; import java.util.function.Function; class Node<T> { T val; Node left, right; Node(T item) { val = item; left = right = null; } } public class MySearch { public static List<Integer> list = new ArrayList<>(); // Java 函数测速 public static void speedTest(Function<Integer, Integer> functionToTest) { // Run for 3 times and get the average double average = 0; System.out.println("==============================="); for (int i = 0; i < list.size(); i += (list.size() - 1) / 2) { System.out.println("Trying to get the " + i + "-th element..."); // 记录函数开始执行的时间 long startTime = System.nanoTime(); // 调用需要测速的函数 functionToTest.apply(list.get(i)); // 记录函数执行结束的时间 long endTime = System.nanoTime(); // 计算函数执行的时间(纳秒) long duration = (endTime - startTime); average += duration; // 打印函数执行的时间(毫秒) System.out.println("Execution time in milliseconds: " + duration / 1000000.0 + '\n'); } System.out.println("Average time in milliseconds: " + average / 3 / 1000000); System.out.println("===============================\n"); } public static int sequentialSearch(int target) { for (int i = 0; i < list.size(); i++) { if (list.get(i) == target) return i; } return -1; } public static int binarySearch(int target) { int left = 0; int right = list.size() - 1; while (left <= right) { int mid = (left + right) / 2; if (list.get(mid) == target) { return mid; // 返回目标元素的下标 } else if (list.get(mid) < target) { left = mid + 1; } else { right = mid - 1; } } return -1; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); Random random = new Random(); for (int i = 0; i < n; i++) { list.add(random.nextInt(10000)); } Collections.sort(list); // Use method // speedTest(MySearch::sequentialSearch); // Use lambda // speedTest((k) -> sequentialSearch(10)); speedTest(MySearch::sequentialSearch); speedTest(MySearch::binarySearch); } }