【问题标题】:same sorting algorithm,same array,but gives different time for sorting when sorting same array few times相同的排序算法,相同的数组,但在对相同的数组排序几次时给出不同的排序时间
【发布时间】:2015-02-02 15:17:34
【问题描述】:

我尝试下面的程序来检查相同的算法是否在同一个数组上运行几次,它会给出不同的排序持续时间。它返回不同的时间。这是为什么 ?我对所有尝试都使用了相同的数组。 包裹分拣;

import java.util.Arrays;
import static sorting.CompareSorting.bubble_sort;
import static sorting.CompareSorting.generate_data;


public class Sorting {


public static void main(String [] args){

    int size = 10000;
    int [] arr = new int[size];
    int [] arr1 = new int[size];
    int [] arr2 = new int[size];
    long startTime;
    long endTime;

    arr = generate_data(size);

    System.arraycopy(arr, 0, arr1, 0, size);
    System.arraycopy(arr, 0, arr2, 0, size);

    System.out.println(Arrays.toString(arr));
    System.out.println(Arrays.toString(arr1));
    System.out.println(Arrays.toString(arr2));

    startTime = System.currentTimeMillis();
    bubble_sort(arr);
    endTime = System.currentTimeMillis();
    System.out.println("1st attempt " + (endTime - startTime));

    startTime = System.currentTimeMillis();
    bubble_sort(arr1);
    endTime = System.currentTimeMillis();
    System.out.println("2nd attempt " + (endTime - startTime));

    startTime = System.currentTimeMillis();
    bubble_sort(arr2);
    endTime = System.currentTimeMillis();
    System.out.println("3rd attempt " + (endTime - startTime));

    }
}

这是排序方法

static void bubble_sort(int [] data) { 

    int i,j,tmp;
    for(i = data.length ; i >= 0 ; i-- ){

        for(j = 0 ; j < data.length - 1 ; j++ ){

            if(data[j] > data[j + 1]){

                tmp = data[j];

                data[j] = data[j + 1];

                data[j + 1] = tmp;

            }

        }

    }

}

返回值: 第一次尝试 438 第二次尝试 359 第三次尝试 297

【问题讨论】:

  • 这不是在 Java 中进行基准测试的正确方法。你可以在这里阅读更多信息:stackoverflow.com/questions/4583175/benchmarking-java-programs.
  • (1) 实验前需要适当的热身。 (2) JIT 编译更有可能在其后期运行时已经优化了部分代码(预热的原因之一) (3) 当试图凭经验确定“哪个更好”时,一次运行什么也没说 - 你应该使用统计工具,在知道结果是statistical significant之前不要试图理解任何东西。
  • 所以编译器优化和识别模式?那么这就是减少我检查每个实例的时间的原因吗?顺便说一句,感谢 kraskevich 和 amit
  • @Dina JIT 是即时编译,它由虚拟机(运行编译后的字节码)实现,并尝试对经常重复的代码片段进行优化。这是在运行时完成的。
  • 运行时间在非硬实时系统上是不确定的。因为系统同时忙于做许多其他事情,而内存访问遵循极其复杂的不可重复行为。

标签: arrays algorithm sorting


【解决方案1】:

Java 使用 JVM(Jav 虚拟机)来运行我们使用 Java 制作的应用程序。一旦运行,它就会优化代码。因此,当您尝试对数组进行三四次排序时,它会优化代码,从而减少运行时间。 结帐ThisThis

【讨论】:

  • 感谢 Thisaru 的回答 :)
猜你喜欢
  • 2021-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多