阅读为什么处理排序数组比处理未排序数组更快?,我在主循环中添加了一个额外的测试。似乎这个额外的测试使程序更快。
int main()
{
// Generate data
const unsigned arraySize = 32768;
int data[arraySize];
for (unsigned c = 0; c < arraySize; ++c)
data[c] = std::rand() % 256;
//Don't sort the array
//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];
//With this additional test, execution becomes faster
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;
}
我得到大约 4.2 秒的附加测试和 18 秒没有附加测试。额外的测试不应该让程序变慢而不是让它变快吗?