小辉程序员之路, since 1996 http://www.xiaohui.com
乐走天涯: 工作并快乐着,职业并休闲着
 » 首页 > MMX 优化: How to optimize for the Pentium family of microprocessors

22.4. Avoiding conditional jumps by using flags (all processors)


http://www.XiaoHui.com 日期: 2000-04-01 13:00

22.4. Avoiding conditional jumps by using flags (all processors)

The most important jumps to eliminate are conditional jumps, especially if they are poorly predictable. Sometimes it is possible to obtain the same effect as a branch by ingenious manipulation of bits and flags. For example you may calculate the absolute value of a signed number without branching:

CDQ XOR EAX,EDX SUB EAX,EDX(On PPlain and PMMX, use MOV EDX,EAX / SAR EDX,31 instead of CDQ).

The carry flag is particularly useful for this kind of tricks:

Setting carry if a value is zero: CMP [VALUE],1

Setting carry if a value is not zero: XOR EAX,EAX / CMP EAX,[VALUE]

Incrementing a counter if carry: ADC EAX,0

Setting a bit for each time the carry is set: RCL EAX,1

Generating a bit mask if carry is set: SBB EAX,EAX

Setting a bit on an arbitrary condition: SETcond AL

Setting all bits on an arbitrary condition: XOR EAX,EAX / SETNcond AL / DEC EAX

(remember to reverse the condition in the last example)

The following example finds the minimum of two unsigned numbers: if (b < a) a = b;

SUB EBX,EAX SBB ECX,ECX AND ECX,EBX ADD EAX,ECX

The next example chooses between two numbers: if (a != 0) a = b; else a = c;

CMP EAX,1 SBB EAX,EAX XOR ECX,EBX AND EAX,ECX XOR EAX,EBX

Whether or not such tricks are worth the extra code depends on how predictable a conditional jump would be, whether the extra pairing or scheduling opportunities of the branch-free code can be utilized, and whether there are other jumps following immediately after which could suffer the penalties of consecutive jumps.

Tags: MMX 优化



 文章评论

目前没有任何评论.

↓ 快抢占第1楼,发表你的评论和意见 ↓
 
发表你的评论
如果你想针对此文发表评论, 请填写下列表单:
姓名: * 必填
E-mail: 可选 (不会被公开)
反垃圾广告: 为了防止广告机器人自动发贴, 请计算下列表达式的值:
10 + 16 = * 必填
评论内容:
* 必填
你可以使用下列标签修饰文字:
[b] 文字 [/b]: 加粗文字
[quote] 文字 [/quote]: 引用文字

 

小辉程序员之路 建站于 1997 ◇ 做一名最好的开发者是我不变的理想……
Copyright(C) 1997-2009 XiaoHui.com   All rights reserved
声明:站内所有原创文字,未经许可,均可转载、复制。
转载时必须以链接形式注明作者和原始出处