9 ms·
On one hand, I found this comment from Linus about CMOV in 2007, explaining that CMOV is generally a bad idea (but maybe it changed in 13 years) : https://yarch
by antpls 6y ago
On one hand, I found this comment from Linus about CMOV in 2007, explaining that CMOV is generally a bad idea (but maybe it changed in 13 years) : https://yarchive.net/comp/linux/cmov.html https://yarchive.net/comp/linux/cmov.html
On the other hand : "The slowdown we’ve measured here is directly related to NOT having CMOV available to us through the CoreCLR JIT."
I guess you would need to benchmark your program on Intel, AMD and ARM with CMOV and without to have a definitive answer.
- throwaway_pdp09 6y agoI didn't buy linus' argument that CMOV was necessarily slow. Anyway, agner fog's instructions stuff (http://www.agner.org/optimize/instruction_tables.pdf http://www.agner.org/optimize/instruction_tables.pdf) says that CMOV has a 1 cycle latency on skylake.
- CalChris 6y agoLinus made that rant in 2007 [1]. He was right back then for circa 2007 hardware but Intel has improved CMOV quite a bit over the 13 years since. Intel now recommends CMOV for unpredictable branches in their Intel® 64 and IA-32 Architectures Optimization Reference Manual as Assembly/Compiler Coding Rule 2: "Use the SETCC and CMOV instructions to eliminate unpredictable conditional branches where possible. Do not do this for predictable branches. Do not use these instructions to eliminate all unpredictable conditional branches (because using these instructions will incur execution overhead due to the requirement for executing both paths of a conditional branch). In addition, converting a conditional branch to SETCC or CMOV trades off control flow dependence for data dependence and restricts the capability of the out-of-order engine. When tuning, note that all Intel 64 and IA-32 processors usually have very high branch prediction rates. Consistently mispredicted branches are generally rare. Use these instructions only if the increase in computation time is less than the expected cost of a mispredicted branch." NB: Intel is recommending CMOV for unpredictable branches. For well predictable branches, they're recommending ... branches. [1] https://yarchive.net/comp/linux/cmov.html https://yarchive.net/comp/linux/cmov.html
- throwaway_pdp09 6y agoThat was a dumb oversight on my part not to think to mention this vital point. Thanks. (also thanks for SETcc, I didn't know of this instruction)
- devit 6y agoIf the conditional is almost always true or almost always false and the CPU has a branch predictor, then a branch is likely faster; otherwise, the CMOV will be faster. Obviously a CPU could use a predictor for CMOVs as well, although I think the commonly used CPUs don't (but not too sure).
- blattimwind 6y agoLinus specifically explains that for a predictable predicate a branch is preferable and why, while for an unpredictable predicate a conditional move is preferable.