NASM Forum > Programming with NASM
How are you multiplying by 3
mik3ca:
ok, I wasn't sure the OP was interested in LEA, and yes I am aware that MUL is a slow operation, but I find when I do coding, I start with simple first to get the job done then I optimize for speed.
fredericopissarra:
--- Quote from: mik3ca on February 27, 2021, 05:47:53 AM ---ok, I wasn't sure the OP was interested in LEA, and yes I am aware that MUL is a slow operation, but I find when I do coding, I start with simple first to get the job done then I optimize for speed.
--- End quote ---
But using LEA to multiply by a constant is simplier that using mov/mul/mov combination, and as debs3759 said, you avoid destroying the contents of one of the 6 still available general purpose registers (EDX) and affecting the flags. So, multiplying, sometimes, is easier to do (and faster) using LEA:
--- Code: ---shl ebx,1 ; *2 (+flags)
lea ebx,[ebx+ebx*2] ; *3
shl ebx,2 ; *4 (+flags)
lea ebx,[ebx+ebx*4] ; *5
shl ebx,1 ; *6 (+flags)
lea ebx,[ebx+ebx*2]
; *7 needs to use one more register:
mov ecx,ebx
shl ebx,3
sub ebx,ecx
shl ebx,3 ; *8 (+flags)
lea ebx,[ebx+ebx*8] ; *9
lea ebx,[ebx+ebx*4] ; *10 (+flags)
shl ebx,1
--- End code ---
Notice there's no need to slower MUL instruction.
fredericopissarra:
Ahhh... one more thing... NASM allows the use of 1,2,3,4,5,8 and 9 as scale in effective address calculations, like:
--- Code: ---lea eax,[3*eax]
--- End code ---
It, automatically, converts this to
--- Code: ---lea eax,[eax+2*eax]
--- End code ---
This way you can multiply by 27, for example, as:
--- Code: ---lea eax,[3*eax]
lea eax,[9*eax]
--- End code ---
As a general rule: If multiplication by a constant can be done in 1 cycle (2 LEAs can be "paired", even in 'out of order" instructions execution), then, I use LEA, otherwise, IMUL, as in:
--- Code: ---imul eax,eax,14 ; cannot be done in 1 cycle using LEAs
--- End code ---
Navigation
[0] Message Index
[*] Previous page
Go to full version