The purpose of cmov
is to allow software (in some cases) to avoid a branch.
For example, if you have this code:
cmp eax,ebx
jne .l1
mov eax,edx
.l1:
…then when a modern CPU sees the jne
branch it will take a guess about whether the branch will be taken or not taken, and then start speculatively executing instructions based on the guess. If the guess is wrong there’s a performance penalty, because the CPU has to discard any speculatively executed work and then start fetching and executing the correct path.
For a conditional move (e.g. cmove eax,edx
) the CPU doesn’t need to guess which code will be executed and the cost of a mispredicted branch is avoided. However, the CPU can’t know if the value in eax
will change or not, which means that later instructions that depend on the results of the conditional move have to wait until the conditional move completes (instead of being speculatively executed with an assumed value and not stalling). 我的理解是,它只是通过不去预测这种方式,来避免预测错了重来。就像你只要不写代码,就不会有bug。
This means that if the branch can be easily predicted a branch can be faster; and if the branch can’t be easily predicted the condition move can be faster.
Note that a conditional move is never strictly needed (it can always be done with a branch instead) - it’s more like an optional optimization.
Reference: CSAPP Section 5.12 - Understanding Memory Performance
需要指出的是,不是所有的条件行为都能用条件数据传送来实现,所以无可避免地在某些情况中,程序员会写出导致条件分支的代码,而对于这些条件分支,处理器用分支预测可能会处理得很糟糕。
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://hanquan.blog.csdn.net/article/details/122283216
内容来源于网络,如有侵权,请联系作者删除!