12. 了解处理器
Nehalem E5620
• 长流水线 >= 15级
• X86指令解释为微
指令后乱序执行
o 等待执行的微指令放在
Reserveration Station
o 多个ALU运算单元并发、
乱序执行
o Reorder Buffer中实现串
行化
o Instruction Retirement
19. 指令量化分析
• 取指令,每个16字节/cycle
• X86指令解析为微指令
o 简单指令3条/cycle
o 复杂指令1条/cycle
• 保留站到EU的Port,总共6个
o P0,P1,P5到ALU单元
o P2,P3,P4到Load/Store单元
• Instruction Retirement,4条μop/cycle
• Dependency Chain长度
20. 指令优化
• 长流水线 >= 15级
o Branch prediction miss性能损耗大
• 减少Branch prediction miss率
o 减少/消除conditional branch
• Bit运算代替比较
• Comvg指令代替比较
• 充分发挥Intel处理器乱序执行的能力
o 避免指令间存在long dependency chain
o 避免指令间隐性的依赖关系,例如对eflags的依赖
21. 消除Conditional Branch
• 如何消除这个if语句 • Bit运算版本1
if (a < b) { int mask = (a-b) >> 31;
r = c; r = (mask & c) | (~mask & d);
} else {
r = d; • Bit运算版本2
} int mask = (a-b) >> 31;
r = d + mask & (c-d);
• cmovg版本
r = (a < b) ?c : d;
22. 不要滥用CMOV指令
CMOV (and, more generically, any
"predicated instruction") tends to
generally a bad idea on an
aggressively out-of-order CPU.
—— Linux Torvalds
25. 量化分析
指令 μop P0/1/5 P0 P1 P5 P2 P3 P4
mov 0x70(%rdi),%edx 6 3 x x x 3
lea -0xf540(%r9),%eax 1 1 1
sar $0x1f,%eax 1 1 x x
sub $0xe76606,%edx 1 1 x x x
and $0x1d5c6,%eax 1 1 x x x
sar $0x1f,%edx 1 1 x x
add $0x3cc1,%eax 1 1 x x x
and $0x6079,%edx 1 1 x x x
sub $0x50fd,%edx 1 1 x x x
cmpl $0xfe3f93,0xb8(%rdi) 1 1 x x x 1
cmovg %eax,%edx 2 2 x x x
lea (%rdx,%rcx,1),%r8d 1 1 1
jg 0x403e18 1 1 1
总和 19 16 4
需要时钟周期 4.75 5.3 4
26. 量化分析
指令 μop P0/1/5 P0 P1 P5 P2 P3 P4
mov 0x70(%rdi),%edx 6 3 x x x 3
lea -0xf540(%r9),%eax 1 1 1
sar $0x1f,%eax 1 1 x x
理论值 5.3个时钟周期x
sub $0xe76606,%edx 1 1 x x x
and $0x1d5c6,%eax 1 1 x x
sar $0x1f,%edx 实际值 5.5个时钟周期x
1 1 x
add $0x3cc1,%eax 1 高度契合
1 x x x
and $0x6079,%edx 1 1 x x x
sub $0x50fd,%edx 1 1 x x x
cmpl $0xfe3f93,0xb8(%rdi) 1 1 x x x 1
cmovg %eax,%edx 2 2 x x x
lea (%rdx,%rcx,1),%r8d 1 1 1
jg 0x403e18 1 1 1
总和 19 16 4
需要时钟周期 4.75 5.3 4