【问题标题】:x86 assembly programming loops with ecx and loop instruction versus jmp + j<condition>带有 ecx 和循环指令的 x86 汇编编程循环与 jmp + j<condition>
【发布时间】:2011-10-11 22:50:37
【问题描述】:

我目前正在学习 x86 汇编语言,想知道实现循环的更好方法是什么。一种方法是将一个值移动到 ecx 寄存器并使用循环指令,另一种方法是使用 jmp 指令,然后进入循环体,然后有条件地跳转到循环体的开头。我猜第一个的可读性会更好,但除此之外我不知道为什么要使用它。

【问题讨论】:

  • 从不知道/不知道何时接受它,因为我猜总有更好的答案?这真的很重要吗?因为我真的不知道。
  • 相关:Why are loops always compiled like this?:在 asm 中使用 do{}while() 结构几乎总是最好的,在底部有一个条件分支。如果循环可能需要运行 0 次,那么 jmp to the bottom 是一种策略,但通常不是最好的。

标签: loops assembly x86


【解决方案1】:

当您提到 jmp+body+test 时,我相信您是在谈论高级语言中 while 循环的翻译。第二种方法是有原因的。一起来看看吧。

考虑

x = N
while (x != 0) {
    BODY
    x--
}

天真的方式是

    mov ecx, N      ; store var x in ecx register
top:
    cmp ecx, 0      ; test at top of loop
    je bottom       ; loop exit when while condition false
    BODY
    dec ecx
    jmp top
bottom:

这有 N 个条件跳转和 N 个无条件跳转。

第二种方式是:

    mov ecx, N 
    jmp bottom
top:
    BODY
    dec ecx
bottom:
    cmp ecx, 0
    jne top

现在我们仍然进行 N 次条件跳转,但我们只进行一次无条件跳转。节省一点点,但它可能很重要,尤其是因为它处于循环状态。

现在你确实提到了loop 指令,它本质上是

dec ecx
cmp ecx, 0
je somewhere

你会怎么做呢?大概是这样的:

    mov ecx, N
    cmp ecx, 0       ; Must guard against N==0
    je bottom
top:
    BODY
    loop top         ; built-in dec, test, and jump if not zero
bottom:

这是一个典型的 CISC 处理器的小解决方案。它比上面的第二种方式更快吗?这在很大程度上取决于架构。如果您真的想了解更多信息,我建议您研究一下loop 指令在 IA-32 和 Intel 64 处理器架构中的性能。

【讨论】:

猜你喜欢
  • 2016-11-01
  • 1970-01-01
  • 2017-01-23
  • 1970-01-01
  • 1970-01-01
  • 2013-07-25
  • 1970-01-01
  • 2012-11-19
  • 1970-01-01
相关资源
最近更新 更多