Java 数据结构基准测试

Java Data Structure Benchmark

所以我对编程还是很陌生,我只是想知道我是否正确地执行了这些基准测试。对于队列,我基本上给它一个充满整数的列表,我会计算它在列表中找到一个数字需要多长时间。至于 HashMap 它基本上是相同的想法,我会计算从列表中获取数字需要多长时间。同样对于他们两个,我也会计算他们删除列表内容需要多长时间。对此的任何帮助将不胜感激。谢谢!

// Create a queue, and test its performance
PriorityQueue<Integer> queue = new PriorityQueue <> (list);
System.out.println("Member test time for Priority Queue is " +
        getTestTime(queue) + " milliseconds");
      System.out.println("Remove element time for Priority Queue is " +
        getRemoveTime(queue) + " milliseconds");

// Create a hash map, and test its performance
HashMap<Integer, Integer> newmap = new HashMap<Integer, Integer>();
 for (int i = 0; i <N;i++) {
  newmap.put(i, i);
}
System.out.println("Member test time for hash map is " +
        getTestTime1(newmap) + " milliseconds");
 System.out.println("Remove element time for hash map is " +
        getRemoveTime1(newmap) + " milliseconds");
}



public static long getTestTime(Collection<Integer> c) {
  long startTime = System.currentTimeMillis();

 // Test if a number is in the collection
 for (int i = 0; i < N; i++)
   c.contains((int)(Math.random() * 2 * N));

return System.currentTimeMillis() - startTime; 
}

 public static long getTestTime1(HashMap<Integer,Integer> newmap) {
   long startTime = System.currentTimeMillis();

     // Test if a number is in the collection
     for (int i = 0; i < N; i++)
      newmap.containsKey((int)(Math.random() * 2 * N));

   return System.currentTimeMillis() - startTime; 
 }

public static long getRemoveTime(Collection<Integer> c) {
 long startTime = System.currentTimeMillis();

  for (int i = 0; i < N; i++)
   c.remove(i);

 return System.currentTimeMillis() - startTime; 
}
public static long getRemoveTime1(HashMap<Integer,Integer> newmap) {
    long startTime = System.currentTimeMillis();

     for (int i = 0; i < N; i++)
       newmap.remove(i);

      return System.currentTimeMillis() - startTime; 
   }
}

我有两个建议。首先,在进行基准测试时,在您正在评估的代码之前和之后立即执行最少的工作。您不希望基准 activity 影响结果。

其次,System.currentTimeMillis() 可以根据 OS,仅在 10 毫秒内准确。最好使用 System.nanoTime(),它精确到大约 200 纳秒。除以 1_000_000 得到毫秒。

实际上,

final long startNanos, endNanos;
startNanos = System.nanoTime();
// your code goes here
endNanos = System.nanoTime();
// display the results of the benchmark