有没有办法优化这个x86汇编代码?

Bru*_*uno 1 x86 assembly

假设您在eax,ecx中获得了值.编写一段计算5*eax + 3*ecx + 1的代码,并将结果存储在eax中.(*表示这里的乘法).

我的代码:

;Initialize the values in eax and ecx
mov eax,3
mov ecx,4
;Compute 3*ecx
mov ebx,eax
mov eax,ecx
mov edx,3
mul edx
; Compute 5*eax
mov ecx,eax
mov eax,ebx
mov edx,5
mul edx
; Compute 5*eax + 3*ecx + 1
lea eax,[ecx + eax]
inc eax
Run Code Online (Sandbox Code Playgroud)

Mic*_*ael 6

如果通过"优化"表示优化指令计数,那么请确保使用lea更多:

;Initialize the values in eax and ecx
mov eax,3
mov ecx,4

;Compute 3*ecx
lea ecx,[ecx*2 + ecx]

; Compute 5*eax
lea eax,[eax*4 + eax]

; Compute 5*eax + 3*ecx + 1
lea eax,[ecx + eax + 1]
Run Code Online (Sandbox Code Playgroud)

如果我的眼睛正确地为我服务,那么机器代码大小也减少了16个字节.

规则支配,你可以用什么计算lea的部分列出指定偏移英特尔的手册.

  • 如果您的目标是对一段代码进行速度优化或大小优化,那么请选择最佳指令来实现该目标(注意:更少的指令并不一定意味着更小的机器代码或更快的代码).否则,只需按照您最容易理解的方式编写它. (2认同)

Spa*_*rky 5

迈克尔(最优秀的)解决方案可以稍微针对大小进行优化(缩短1个字节),但这需要先进行一点代数操作.

  5*eax + 3*ecx + 1
= 2*eax + 3*eax + 3*ecx + 1
= 2*eax + 3*(eax + ecx) + 1
Run Code Online (Sandbox Code Playgroud)

这可以通过...解决

(Excluding initialization of EAX and ECX)
add ecx, eax                  ; 2 bytes
lea ecx,[ecx*2 + ecx]         ; 3 bytes
lea eax,[eax*2 + ecx + 1]     ; 4 bytes
Run Code Online (Sandbox Code Playgroud)