2014-12-07 67 views
0

我想知道如何可以优化这个代码更多一点。现在他有467k和59条线。我如何优化此代码? [大会8086字母金字塔]

数据段:

code_char db 'A' 
counter_space db 39 
counter_char dw 1 
counter_rows dw 25 

程序段:

rows: 

mov cl, counter_space ;here I write space 
mov ah,02h 
mov dl,'' 
space: 
int 21h 
loop space 

mov cx, counter_char ;here I write letters 
mov ah,02h 
mov dl,code_char 
letters: 
int 21h 
loop letters 

mov ah,02h ;here I go to another line(enter) 
mov dl,0ah 
int 21h 

INC code_char ;here I change the value of variable's 
DEC counter_space 
ADD counter_char,2 
DEC counter_rows 

mov cx,counter_rows ;here I count the rows to 25 
loop rows 

mov ah,01h ;here I w8 to any key 
int 21h 

      mov  ah,4ch 
      mov  al,0 
      int  21h 

如果您有任何建议,请发表评论。 我刚开始学习Assembly。

+0

你的目标是优化速度或大小?你在用什么汇编语言?以及你用于汇编程序的命令行参数是什么?代码看起来像MS-DOS环境的16位代码('int 21h'等等),所以它已经过时了。如果使用16位代码不是老师给出的要求,而且您现在也不打算写自己的引导加载程序,我建议您学习现代的32位或64位x86/x86-64程序集,而不是过时的16位x86汇编。 – nrz 2014-12-07 15:06:37

+0

我必须对大小(行数,内存)进行优化。您对其MS-DOS环境的16位是正确的)。我必须使用16位。 – Lukas 2014-12-07 15:11:44

+0

你正在使用什么汇编程序和什么命令行参数?你用'(线,内存)'来表示什么?在我看来,对代码行进行优化对于汇编代码来说没有多大意义。如果你真的需要,只需使用'db'编写所有的代码,你只能得到1行代码......你的意思是你的EXE文件的大小是467千字节?如果您确实需要优化可执行文件大小,请将您的可执行文件作为COM文件。之后,检查代码中所有指令的编码大小,并查找缩短可执行文件的位置。 – nrz 2014-12-07 15:38:41

回答

0

您可以使用所有其他变量可以从counter_rows变量来计算的事实,所以你真的只需要一个变量:

code_char  = 'A' + 25 - counter_rows 
counter_space = counter_rows + 14 
counter_char = 51 - counter_rows * 2 

由于counter_rows是您的外环计数器,你可以只保留它一直在寄存器中,而不是为它分配内存。这使得可以在没有任何内存引用的情况下运行该程序。

还有一些小的优化可以完成。除第一次呼叫外,您不需要将ah寄存器设置为02h。当为按键呼叫设置ah01h时,您可以减少寄存器,因为您知道它之前为02h。您可以设置ax而不是分别设置ahal

如果我计算正确,应该采取实际的代码,并从59到41的数据字节下来:

mov bx, 25 ;counter_rows 
rows: 

    ;here I write space 
    mov cx, bx ; counter_space = counter_rows + 14 
    add cl, 14 
    mov ah, 02h 
    mov dl, 32 ;space 
    space: 
    int 21h 
    loop space 

    ;here I write letters 
    mov cl, 51 ;counter_char = 51 - counter_rows * 2 
    sub cl, bl 
    sub cl, bl 
    ;mov ah, 02h - already set 
    mov dl, 65 + 25 ;code_char = 'A' + 25 - counter_rows 
    sub dl, bl 
    letters: 
    int 21h 
    loop letters 

    ;here I go to another line(enter) 
    ;mov ah, 02h - already set 
    mov dl, 0ah 
    int 21h 

    dec bx 
jnz rows 

;here I wait for any key 
dec ah ;02h - 1 = 01h 
int 21h 

mov ax,4c00h ;set ah and al in one go 
int 21h