在C ...的If-Else和Ternary运算符之间的速度差异? [英] Speed difference between If-Else and Ternary operator in C...?
问题描述
所以在一个同事的建议下,我只是测试了三元运算符和等价的If-Else块之间的速度差异...并且似乎三元运算符产生的代码在1x和2x之间比If-其他。我的代码是:
gettimeofday(& tv3,0);
for(i = 0; i {
a = i& 1;
if(a)a = b; else a = c;
}
gettimeofday(& tv4,0);
gettimeofday(& tv1,0);
for(i = 0; i {
a = i& 1;
a = a? b:c;
}
gettimeofday(& tv2,0);
(对不起,使用gettimeofday而不是clock_gettime ...我会努力改善自己。 p>
我尝试更改块的时间顺序,但结果似乎持续。是什么赋予了?此外,If-Else在执行速度方面显示出更多的可变性。我应该检查gcc生成的程序集吗?
顺便说一句,这是在优化级别零(-O0)。 p>
我是想象这个,还是有一些我没有考虑到的,或者这是一个机器相关的东西,还是什么?
很有可能三元运算符被编译成 cmov
,而if / else结果在 cmp
+ jmp
。只需看看程序集(使用-S)就可以了。启用优化后,无论如何,任何更好的编译器都应该在两种情况下产生相同的代码。
So at the suggestion of a colleague, I just tested the speed difference between the ternary operator and the equivalent If-Else block... and it seems that the ternary operator yields code that is between 1x and 2x faster than If-Else. My code is:
gettimeofday(&tv3, 0);
for(i = 0; i < N; i++)
{
a = i & 1;
if(a) a = b; else a = c;
}
gettimeofday(&tv4, 0);
gettimeofday(&tv1, 0);
for(i = 0; i < N; i++)
{
a = i & 1;
a = a ? b : c;
}
gettimeofday(&tv2, 0);
(Sorry for using gettimeofday and not clock_gettime... I will endeavor to better myself.)
I tried changing the order in which I timed the blocks, but the results seem to persist. What gives? Also, the If-Else shows much more variability in terms of execution speed. Should I be examining the assembly that gcc generates?
By the way, this is all at optimization level zero (-O0).
Am I imagining this, or is there something I'm not taking into account, or is this a machine-dependent thing, or what? Any help is appreciated.
There's a good chance that the ternary operator gets compiled into a cmov
while the if/else results in a cmp
+jmp
. Just take a look at the assembly (using -S) to be sure. With optimizations enabled, it won't matter any more anyway, as any good compiler should produce the same code in both cases.
这篇关于在C ...的If-Else和Ternary运算符之间的速度差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!