为什么处理排序数组要比处理未排序数组快?

偶尔善良 提交于 2020-08-11 04:29:30

问题:

Here is a piece of C++ code that shows some very peculiar behavior. 这是一段C ++代码,显示了一些非常特殊的行为。 For some strange reason, sorting the data miraculously makes the code almost six times faster: 出于某些奇怪的原因,奇迹般地对数据进行排序使代码快了将近六倍:

#include <algorithm>
#include <ctime>
#include <iostream>

int main()
{
    // Generate data
    const unsigned arraySize = 32768;
    int data[arraySize];

    for (unsigned c = 0; c < arraySize; ++c)
        data[c] = std::rand() % 256;

    // !!! With this, the next loop runs faster.
    std::sort(data, data + arraySize);

    // Test
    clock_t start = clock();
    long long sum = 0;

    for (unsigned i = 0; i < 100000; ++i)
    {
        // Primary loop
        for (unsigned c = 0; c < arraySize; ++c)
        {
            if (data[c] >= 128)
                sum += data[c];
        }
    }

    double elapsedTime = static_cast<double>(clock() - start) / CLOCKS_PER_SEC;

    std::cout << elapsedTime << std::endl;
    std::cout << "sum = " << sum << std::endl;
}
  • Without std::sort(data, data + arraySize); 没有std::sort(data, data + arraySize); , the code runs in 11.54 seconds. ,代码将在11.54秒内运行。
  • With the sorted data, the code runs in 1.93 seconds. 使用排序的数据,代码将在1.93秒内运行。

Initially, I thought this might be just a language or compiler anomaly, so I tried Java: 最初,我认为这可能只是语言或编译器异常,所以我尝试了Java:

import java.util.Arrays;
import java.util.Random;

public class Main
{
    public static void main(String[] args)
    {
        // Generate data
        int arraySize = 32768;
        int data[] = new int[arraySize];

        Random rnd = new Random(0);
        for (int c = 0; c < arraySize; ++c)
            data[c] = rnd.nextInt() % 256;

        // !!! With this, the next loop runs faster
        Arrays.sort(data);

        // Test
        long start = System.nanoTime();
        long sum = 0;

        for (int i = 0; i < 100000; ++i)
        {
            // Primary loop
            for (int c = 0; c < arraySize; ++c)
            {
                if (data[c] >= 128)
                    sum += data[c];
            }
        }

        System.out.println((System.nanoTime() - start) / 1000000000.0);
        System.out.println("sum = " + sum);
    }
}

With a similar but less extreme result. 具有相似但不太极端的结果。


My first thought was that sorting brings the data into the cache, but then I thought how silly that was because the array was just generated. 我首先想到的是排序将数据带入缓存,但是后来我想到这样做是多么愚蠢,因为刚刚生成了数组。

  • What is going on? 到底是怎么回事?
  • Why is processing a sorted array faster than processing an unsorted array? 为什么处理排序数组要比处理未排序数组快?

The code is summing up some independent terms, so the order should not matter. 该代码总结了一些独立的术语,因此顺序无关紧要。


解决方案:

参考一: https://stackoom.com/question/l6rh/为什么处理排序数组要比处理未排序数组快
参考二: https://oldbug.net/q/l6rh/Why-is-processing-a-sorted-array-faster-than-processing-an-unsorted-array
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!