在stackoverflow看到的一篇文章
http://stackoverflow.com/questions/11227809/why-is-processing-a-sorted-array-faster-than-an-unsorted-array
排序后竟然比不排序的速度更快,排序后快了几乎两倍的时间。很惊奇
#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;
}
某个大牛说到,在if语句那里有分支预测(branch prediction),应该是编译器所做的一种优化。在if语句时,就会假设if语句的执行方向,如果假设正确,那么继续执行,如果假设错误,那么就会花费时间,回到刚才的那一点,再继续执行下去。
If you guess right every time, the execution will never have to stop.
If you guess wrong too often, you spend a lot of time stalling, rolling back, and restarting.
排序前,数字是随机的,预测总是出错,浪费了不必要的时间,排序后,预测的正确性高,速度快。
如果把上面的if判断代码改成下面两句,那么排序后的运行时间大于不排序的时间。
int t = (data[c] - 128) >> 31;
sum += ~t & data[c];
还是看一下源网站,那里讲述的很清楚。