I executed the code from this famous topic Why is processing a sorted array faster than processing an unsorted array?
On my Mac OS Mojave:
//file test.cpp
#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)
{
for (unsigned c = 0; c < arraySize; ++c)
{ // Primary loop
if (data[c] >= 128)
sum += data[c];
}
}
double elapsedTime = static_cast<double>(clock()-start) / CLOCKS_PER_SEC;
std::cout << elapsedTime << '\n';
std::cout << "sum = " << sum << '\n';
}
I compiled it with optimization flags:
g++ -std=c++11 test.cpp -O3 -march=native -o test.out
After running the versions with and without sorting, I found out that my execution times were very close, ~0.37 s. I've tried the following things:
- Used clang instead of g++. Same result.
- Inserted
std::srand(std::time(nullptr));
before random number generator to have a randomized seed. Same result.
Apple LLVM version 10.0.1 (clang-1001.0.46.4)