Wil*_*mKF 8 c++ hardware compiler-construction micro-optimization
对于现代硬件上的典型现代编译器,? :运算符是否会导致影响指令流水线的分支?
换句话说哪个更快,调用两个案例以避免可能的分支:
bool testVar = someValue(); // Used later.
purge(white);
purge(black);
Run Code Online (Sandbox Code Playgroud)
或选择实际需要清除的一个并且只与操作员一起做?::
bool testVar = someValue();
purge(testVar ? white : black);
Run Code Online (Sandbox Code Playgroud)
我知道你不知道purge()需要多长时间,但我只是在这里问一个关于我是否想要两次调用purge()来避免代码中可能的分支的一般性问题.
我意识到这是一个非常小的优化,并没有真正的区别,但仍然想知道.我希望?:不会导致分支,但希望确保我的理解是正确的.
取决于平台.具体来说,它取决于CPU的跳转预测表的大小以及CPU是否允许条件操作(如ARM).
具有条件操作的CPU将强烈支持第二种情况.具有较大跳跃预测表的CPU将支持第一种情况.
真正的答案(与任何其他表现问题一样):衡量和比较.有时其余的代码会抛出曲线球,通常无法预测某些变化的影响.
自Pentium Pro以来,CMOV(条件MOVe)指令已成为x86指令集的一部分.由于常用的编译器选项和C语言的限制,它很少由GCC自动生成.可以通过C程序中的内联汇编插入SETCC/CMOV序列.这应该只是在条件变量是程序的内循环(数百万次执行)中的随机振荡值的情况下才会这样做.在非振荡情况下和简单振荡模式的情况下,现代处理器可以以非常高的准确度预测分支.2007年,Linus Torvalds建议在大多数情况下避免使用CMOV.
英特尔描述了英特尔(R)体系结构软件开发人员手册第2卷:指令集参考手册中的条件性移动:
The CMOVcc instructions check the state of one or more of the status flags in the EFLAGS
register (CF, OF, PF, SF, and ZF) and perform a move operation if the flags are in a specified
state (or condition). A condition code (cc) is associated with each instruction to indicate the
condition being tested for. If the condition is not satisfied, a move is not performed and execution
continues with the instruction following the CMOVcc instruction.
These instructions can move a 16- or 32-bit value from memory to a general-purpose register or
from one general-purpose register to another. Conditional moves of 8-bit register operands are
not supported.
The conditions for each CMOVcc mnemonic is given in the description column of the above
table. The terms “less” and “greater” are used for comparisons of signed integers and the terms
“above” and “below” are used for unsigned integers.
Because a particular state of the status flags can sometimes be interpreted in two ways, two
mnemonics are defined for some opcodes. For example, the CMOVA (conditional move if
above) instruction and the CMOVNBE (conditional move if not below or equal) instruction are
alternate mnemonics for the opcode 0F 47H.
Run Code Online (Sandbox Code Playgroud)