EDIT: I know about failed branch predictions, that's the main reason that led me to ask this question. If there's more branches, I'd expect there to be more failed predictions. The first and second parts of my code are precisely the same, apart from an extra branch in the second part. This extra branch will always evaluate to true
, but still requires the evaluation of i%2. Why is it faster? Compiler optimizations solve the issue, but a new one question arises. Why was it happening when the optimizations were turned off?
Original post:
I am trying to understand just how if
and else
statements affect the performance of my codes in C++. These are the parameters and code I've used:
Compiler: g++ (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609
Compilation: g++ -Wall ifs_comparison.cpp -o ifs_comparison
int main(){
clock_t t;
int N = 100000000;
int even_odd[2];
// Using if statements and being stupid with the else statement.
// This uses more calculations than the ones that should be needed.
even_odd[0] = 0;
even_odd[1] = 0;
t = clock();
for(int i = 0; i < N; i++){
if(i%2==0)
even_odd[0]++;
else
{
if(i%2==1)
even_odd[1]++;
}
}
t = clock() - t;
std::cout << "Using 'if' statements and being stupid with the 'else' statement.\n";
std::cout << "This took " << ((float)t)/CLOCKS_PER_SEC << "seconds\n";
std::cout << "Repeat the task but with a simpler 'else' statement\n";
// Using if statements but simplifying the else statement
// Reset the variables
even_odd[0] = 0;
even_odd[1] = 0;
t = clock();
for(int j = 0; j < N; j++)
{
if(j%2==0)
even_odd[0]++;
else
even_odd[1]++;
}
t = clock() - t;
std::cout << "This took " << ((float)t)/CLOCKS_PER_SEC << "seconds\n";
std::cout << "Repeat the task but without 'if' statements\n";
// Not using 'if' statements
// Reset the variables
even_odd[0] = 0;
even_odd[1] = 0;
t = clock();
for(int k = 0; k < N; k++)
even_odd[k%2]++;
t = clock()-t;
std::cout << "This took " << ((float)t)/CLOCKS_PER_SEC << "seconds\n";
return 0;
}
The output is:
Using 'if' statements and being stupid with the 'else' statement.
This took 0.262272seconds
Repeat the task but with a simpler 'else' statement
This took 0.294445seconds
Repeat the task but without 'if' statements
This took 0.238543seconds
As expected, the part without if
statements runs faster. So I thought I'd see just how much faster it'd be if I simplified the else statement by removing the evaluation i%2
. To my surprise, it was actually slower! What's going on? Can someone point me to a good reference on just how these if
and else
statements work?