Java 如何度量为每个排序算法对数组进行排序所需的时间?

Java 如何度量为每个排序算法对数组进行排序所需的时间?,java,sorting,Java,Sorting,我正在尝试创建一个程序,用于测量每个排序算法对50个随机整数进行排序所需的时间。首先打印未排序的数组,然后打印已排序的数组。当测量的时间为0时,每个排序算法的输出。我可以在代码中做些什么来做得更好 public static void main(String[] args) { System.out.println("Please enter the size of array:"); Scanner input = new Scanner(Syste

我正在尝试创建一个程序,用于测量每个排序算法对50个随机整数进行排序所需的时间。首先打印未排序的数组,然后打印已排序的数组。当测量的时间为0时,每个排序算法的输出。我可以在代码中做些什么来做得更好

  public static void main(String[] args)
      { 

      System.out.println("Please enter the size of array:");
      Scanner input = new Scanner(System.in); 
      int arraySize =input.nextInt(); 
      int[] array = new int[arraySize]; 
      if (arraySize == 50) {

        initValues();
        printValues();
        System.out.println("values is sorted: " + isSorted());
        System.out.println();

        // make call to sorting method here (just remove //)
         selectionSort();
         long startTime = System.currentTimeMillis();
         long total = 0; 
         long stopTime = System.currentTimeMillis();
         long elapsedTime = stopTime-startTime;
         selectionSort(); 
         //bubbleSort();
         //shortBubble();
         //insertionSort();
         //mergeSort(0, SIZE - 1);
         //quickSort(0, SIZE - 1);
         //heapSort();


        printValues();
        System.out.println("values is sorted: " + isSorted());
        System.out.println();
        System.out.println("The time it took to sort was: " +elapsedTime);
        }
      else {
      System.out.println("The size of the array should be 50"); 
      }
     }

提前谢谢你

要正确执行微基准测试非常困难,但从一个非常简单的开始,您可以这样做:

  • 不要使用
    currentTimeMillis
    ,而是使用
    nanoTime
    来测量经过的时间
  • 使用一个循环并进行排序,例如10K次并测量,然后将其除以10K等

  • 您确定
    stopTime
    位于正确位置吗?看起来您在实际进行排序之前先进行了
    elapsedTime
    stopTime
    计算。在执行了希望计时的代码之后,您会希望记录这些值。我想将其放在调用selectionSort()方法之后可以正确地测量它?我想把它放在哪里?我试过这样做,但它也不起作用:selectionSort();long startTime=System.currentTimeMillis();长总计=0;selectionSort();长停止时间=System.currentTimeMillis();long elapsedTime=停止时间开始时间;要测量某些东西,您需要捕获操作前的时间(也称为开始时间)和操作后的时间(称为结束时间)。现在你在之前做这两件事,你的另一个评论在之后做这两件事。不要调用
    selectionSort()
    两次。