您的位置:首页 > 其它

为什么排序后的数组比没有排序过的数组运行快?

2017-07-03 18:01 169 查看
stackoverflow的原文地址:why-is-it-faster-to-process-a-sorted-array-than-an-unsorted-array

问题:

在stackoverflow有人问道:为什么排序后的数组比没有排序过的数组运行快?

#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;
}


在上面这段代码中,如没有std:sort(data,data+arraySize);运行11.54秒,如果有则仅仅运行1.93秒。题者为了知道是不是语言或者编译器问题,也贴出了java的代码。

答案:

原因是分支预测器Branch_predictor在排好序的数组里能更好地预测走if-else的哪一个分支。

if (data[c] >= 128)
sum += data[c];


不想排序可以使用下面这段代码替换上面那段代码。

int t = (data[c] - 128) >> 31;
sum += ~t & data[c];
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐