I find this topic Why is it faster to process a sorted array than an unsorted array? . And try to run this code. And I find strange behavior. If I compile this code with -O3
optimization flag it takes 2.98605 sec
to run. If I compile with -O2
it takes 1.98093 sec
. I try to run this code several times(5 or 6) on the same machine in the same environment, I close all other software(chrome, skype etc).
gcc --versiongcc (Ubuntu 4.9.2-0ubuntu1~14.04) 4.9.2Copyright (C) 2014 Free Software Foundation, Inc.This is free software; see the source for copying conditions. There is NOwarranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
So please can you explain to me why this happens? I read gcc
manual and I see that -O3
includes -O2
. Thank you for help.
P.S. add code
#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;}