Java数据结构基准

时间:2017-12-05 18:49:43

标签: java vector hashmap queue benchmarking

所以我对编程还是比较新的,我只是想知道我是否正确地进行了这些基准测试。对于队列我基本上给它一个填充整数的列表,我会花时间在列表上找到一个数字需要多长时间。至于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; 
   }
}

1 个答案:

答案 0 :(得分:0)

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

其次,根据操作系统,System.currentTimeMillis()只能在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