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];