true
,但仍需要评估i%2。为什么它更快?编译器优化解决了这个问题,但是出现了一个新的问题。为什么在关闭优化时会发生这种情况?
原帖:
我试图了解if
和else
语句如何影响我在C ++中的代码性能。这些是我使用的参数和代码:
编译器:g++ (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609
编译:{{1}}
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;
}
正如所料,没有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
语句的部分运行得更快。因此,如果我通过删除评估if
简化了else语句,我想我还能看到它的速度有多快。令我惊讶的是,它实际上更慢!发生了什么事?有人能指出我对这些i%2
和if
语句如何工作的一个很好的参考?