简体   繁体   English

如何单步测量排序算法的时间?

[英]How can I measure the times of my sorting algorithms in a single step?

I am working on a exercise but I am stuck on one point 我正在做运动,但只坚持一点

I want to measure the sorting times of 3 sorting algorithms (bubble,insertion and selection) using seven different arrays. 我想使用七个不同的数组来测量3种排序算法(气泡,插入和选择)的排序时间。 I have tried multiple ways but I can't measure the sorting time of all three algorithms in a single step for all the arrays. 我尝试了多种方法,但是无法在一个步骤中测量所有数组的所有三种算法的排序时间。 My programme should: 我的程序应:

  • randomly fill the array with integers 用整数随机填充数组
  • sort them 排序
  • measure the times 衡量时间
  • print the times 打印时间

The results are always coming 0 millisecond but it can not be like that because I tried 1million integer array so, there is no possibility for coming 0 millisecond for it.Finally, I tried "for loop " for achieving the what will I do. 结果始终为0毫秒,但不能这样,因为我尝试了100万个整数数组,因此不可能达到0毫秒。最后,我尝试了“ for循环”来实现我的目标。

I should write the all my methods because you may find another errors in other methods. 我应该编写所有方法,因为您可能会在其他方法中发现另一个错误。

public static void randomlyFillArray(int[] array, int a, int b) {
    for (int i = 0; i < array.length; i++) {
        array[i] = randomInt(a, b);
    }
}

public static int randomInt(int a, int b) {
    return (int) ((b - a + 1) * Math.random() + a);

}

public static void SelectionSort(int[] array) {

    for (int i = 0; i < array.length - 1; i++) {
        for (int j = i + 1; j < array.length; j++) {
            if (array[i] > array[j]) {
                // ... Exchange elements
                int temp = array[i];
                array[i] = array[j];
                array[j] = temp;
            }
        }
    }
}

public static void insertionSort(int[] array) {
    int i, j, temp;
    for (i = 1; i < array.length; i++) {
        temp = array[i];
        j = i;
        while (j > 0 && array[j - 1] > temp) {
            array[j] = array[j - 1];
            j--;
        }
        array[j] = temp;
    }
}

public static void bubbleSort(int[] array) {
    boolean swapped = true;
    int j = 0;
    int temp;
    while (swapped) {
        swapped = false;
        j++;
        for (int i = 0; i < array.length - j; i++) {
            if (array[i] > array[i + 1]) {
                temp = array[i];
                array[i] = array[i + 1];
                array[i + 1] = temp;
                swapped = true;
            }
        }
    }
}

public static void main(String[] args) {
    // int[] array500 = new int[500];  //These are my arrays that I should do the process for //each one.
    // int[] array1000 = new int[1000];
    // int[] array5000 = new int[5000];
    // int[] array10000 = new int[10000];
    // int[] array50000 = new int[50000];
    // int[] array100000 = new int[100000];
    // int[] array500000 = new int[500000];
    // int[] array1000000 = new int[1000000];
    for (int i = 0; i < 4; i++) {

        int[] array = new int[500];
        if (i == 1) {
            randomlyFillArray(array, 1, 1000);
            SelectionSort(array);

            long startTime = System.currentTimeMillis();
            long total = 0;

            long stopTime = System.currentTimeMillis();
            long elapsedTime = stopTime - startTime;
            SelectionSort(array);
            System.out.println("SelectionSort for 500 integer :  "
                    + elapsedTime);

        } else if (i == 2) {
            randomlyFillArray(array, 1, 1000);
            insertionSort(array);
            long startTime = System.currentTimeMillis();

            long total = 0;

            long stopTime = System.currentTimeMillis();
            long elapsedTime = stopTime - startTime;
            insertionSort(array);
            System.out.println("InsertionSort for 500 integer :  "
                    + elapsedTime);
        } else if (i == 3) {
            randomlyFillArray(array, 1, 1000);
            bubbleSort(array);

            long startTime = System.currentTimeMillis();
            long total = 0;

            long stopTime = System.currentTimeMillis();
            long elapsedTime = stopTime - startTime;
            bubbleSort(array);

            System.out.println("BubbleSort for 500 integer :  "
                    + elapsedTime);

        }

    }

}

Thank you for your all advices stackoverflow family. 感谢您的所有建议stackoverflow系列。

Sincerely. 真诚。

All your timing blocks look like this: 您所有的时序块如下所示:

randomlyFillArray(array, 1, 1000);
SelectionSort(array);
long startTime = System.currentTimeMillis();
long total = 0;
long stopTime = System.currentTimeMillis();
long elapsedTime = stopTime - startTime;
SelectionSort(array);
System.out.println("SelectionSort for 500 integer :  " + elapsedTime);

You sort, then take the start time, then immediately take the end time, then sort again, then print the times. 您进行排序, 然后采用开始时间,然后立即采用结束时间, 然后再次进行排序,然后打印时间。 You have to take the end time after the sort. 您必须在排序花费结束时间。 If you have a reason for sorting twice ('warming up' the JVM?), make sure that you re-randomize the array before you do the timed sort. 如果您有理由进行两次排序(“预热” JVM吗?),请确保在进行定时排序之前重新对数组进行随机化。 An algorithm's performance for sorting an already sorted array might be much different. 排序已排序数组的算法性能可能会大不相同。

randomlyFillArray(array, 1, 1000);
long startTime = System.currentTimeMillis();
long total = 0;  // this thing is never used...
SelectionSort(array); // move this line between start time and end time!
long stopTime = System.currentTimeMillis();
long elapsedTime = stopTime - startTime;
System.out.println("SelectionSort for 500 integer :  " + elapsedTime);

Also, much of that code is the same for each of those sorts. 而且,对于每种类型的代码,大部分代码都是相同的。 You can move those parts out of the if/else blocks and into the loop, making the whole code more compact and easier to maintain. 您可以将这些部分移出if/else块并移入循环,从而使整个代码更紧凑且更易于维护。 Also, you can create another loop around that one for the different array sizes. 同样,您可以针对不同的阵列大小在该循环周围创建另一个循环。

for (int num : new int[] {500, 1000, 5000, ...}) {
    for (int i = 0; i < 4; i++) {
        String sort = null;
        int[] array = new int[num];
        randomlyFillArray(array, 1, 1000);
        long startTime = System.currentTimeMillis();
        if (i == 1) {
            sort = "SelectionSort";
            SelectionSort(array);
        } else if (i == ...) {
            // analogeous for other sorts
        }
        long stopTime = System.currentTimeMillis();
        long elapsedTime = stopTime - startTime;
        System.out.println(sort + " for " + num + " integers: " + elapsedTime);
    }
}

creating microbenchmarks can be tricky, because the JIT compiles frequently used code, which takes some time of its own... 创建微基准可能很棘手,因为JIT会编译常用的代码,这需要花费一些时间...

so my approach is usually like this: 所以我的方法通常是这样的:

public void measureSorting(int[] array) {
    // this should be sufficiently large
    long start, end;
    randomlyFillArray(array, 1, 1000);

    // warm up JIT - execute without measuring
    SelectionSort(array);
    randomlyFillArray(array, 1, 1000);

    // stop the time
    start = System.currentTimeMillis();
    SelectionSort(array);
    end = System.currentTimeMillis();

    System.out.printf("SelectionSort for %d integer :  %d milliseconds", array.length, end-start);

    // repeat for other algorithms
}

If you are using Java8, you can even create something like this: 如果您使用的是Java8,甚至可以创建如下代码:

public static void measureSorting(int[] array, Consumer<int[]> sortingFunction) {
    // this should be sufficiently large
    long start, end;
    randomlyFillArray(array, 1, 1000);

    // warm up JIT - execute without measuring
    sortingFunction.accept(array);
    randomlyFillArray(array, 1, 1000);

    // stop the time
    start = System.currentTimeMillis();
    sortingFunction.accept(array);
    end = System.currentTimeMillis();

    // repeat for other algorithms

    System.out.printf("%s for %d integer :  %d milliseconds", sortingFunction, array.length, end-start);
}

public static void main(String[] args) {
    // assuming the enclosing class is Sorter
    measureSorting(new int[500], Sorter::SelectionSort);
    measureSorting(new int[500], Sorter::insertionSort);
    measureSorting(new int[500], Sorter::bubbleSort);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何衡量用Java编写的代码的速度? (AI算法) - How can I measure the speed of code written in Java? (AI algorithms) 排序算法-如何在m​​ain中实现我的类:) - Sorting algorithms - how to implement my classes in main :) java如何测量方法调用时间? - java how can I measure method call times? 如何纠正选择和插入排序算法 - How can I rectify my selection and insertion sort algorithms 如何在Java Stream的单个步骤中使用并行执行 - How can I use parallel execution on a single step of a Java Stream 我可以强制我的数据流管道中的一个步骤是单线程的(并且在一台机器上)吗? - Can I force a step in my dataflow pipeline to be single-threaded (and on a single machine)? 如何为JTable中的单个列提供多个排序选项? - How can I provide multiple sorting options for a single column in a JTable? 如何改进此搜索算法运行时? - How can I improve this search algorithms runtime? 如何列出可用的密码算法? - How can I list the available Cipher algorithms? 如何准确测量服务器可以处理多少个套接字连接? - How can I accurately measure how many socket connections my server can handle?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM