Chris
Chris

Reputation: 23

How to optimize the algorithm of this program(write in asm)

The aim of the programme is to add the Hex data from ffff:0-ffff:b
The result of the add will be saved as dx

assume cs:code
code segment
mov ax,0ffffH   ;       set ds
mov ds,ax       ;   point to ffffH

mov ax,4000H    ;       set ss
mov ss,ax       ;   point to 4000H
mov bx,0000H    ;       reset bx
mov sp,0010H    ;       set ss:sp point to 4000:0010

push bx         ;       reset stack
mov cx,000cH    ;       set while number

s:              ;       while point
pop ax          ;       get add result
mov dl,[bx]     ;get the number which is in ffff:0-ffff:b to dl
sub dh,dh       ;set dh=00H
inc bx          ;the bx+1
add dx,ax       ;add result
push dx         ;save the last add result
loop s          ;jmp s:

mov ax,004cH    ;       programme use
int 21H         ;   int 21H to return

code ends
end

Upvotes: 0

Views: 139

Answers (1)

Sep Roland
Sep Roland

Reputation: 39166

Excessive memory use There's no need for the detour over the stack. This also slows down the code.

Redundant register use Currently you're controlling the loop through a separate loop-control-variable (CX), but you can just as well control the loop with the address-variable (BX) that is already available.

Reducing number of iterations Instead of doing 12 additions to the DX register that was cleared beforehand, you can load DX with one of the values and then only do 11 additions.

Below is one possible implementation.

Traversing the memory from top to bottom allows us to not have to cmp the address with some value. We can use the flags obtained from the dec of the address.

  mov bx, 000Ah
  mov dx, 0FFFFh
  mov ds, dx
  inc dx          ; Cheap way to zero DX in this case
  mov dl, [bx+1]  ; Load byte from FFFF:000B
More:
  add dl, [bx]
  adc dh, bh      ; BH=0 throughout the address range
  dec bx
  jns More

  mov ax, 4C00h   ; DOS.TerminateWithReturnCode
  int 21h

Please notice that your program purely by chance was able to exit to DOS with your instructions mov ax,004cH int 21H. From the mention of 4cH it should be clear that the intention was to exit via DOS.TerminateWithReturnCode function 4Ch, but through a lucky inversion you got the old and deprecated DOS.TerminateProgram function 00h.

Upvotes: 1

Related Questions