判断月份天数的MIPS程序优化问询:能否减少标签与分支?
优化MIPS判断月份天数程序:减少分支与标签
我找了一圈,网上好像没看到用MIPS写的判断月份天数的方案(也可能是我搜得不够仔细)。想请教下,我写的这个判断月份天数的MIPS程序能不能用更高效的方式优化,不用这么多标签和分支?
原代码
.data msg : .asciiz "Give the month: " msg1 : .asciiz "This month contains 31 Days." msg2 : .asciiz "This month contains 30 Days." msg3 : .asciiz "This month contains 28/29 Days." .text .globl main main: li $v0,4 la $a0,msg syscall li $v0,5 syscall move $t0,$v0 #t0 contains given month li $t7,7 li $t2,2 li $t1,0 div $t0,$t2 mfhi $t3 mflo $t4 bgt $t0,$t7,etiq3 beq $t0,$t2,etiq2 beqz $t3,etiq1 bgtz $t3,etiq etiq: li $v0,1 addi $a0,$s1,0 syscall li $v0,4 la $a0,msg1 syscall j exit etiq1: li $v0,1 addi $a0,$s0,0 syscall li $v0,4 la $a0,msg2 syscall j exit etiq2: li $v0,1 addi $a0,$s0,0 syscall li $v0,4 la $a0,msg3 syscall j exit etiq3: beqz $t3,etiq bgtz $t3,etiq1 exit: li $v0,10 syscall
原代码问题分析
原代码依赖大量分支和标签,不仅可读性一般,还会增加CPU分支预测的开销;另外代码里存在冗余的数字输出逻辑($s1、$s0初始值为0,输出无意义),完全可以移除。
优化方案:查表法替代分支判断
月份天数是固定规律,我们可以把每个月对应的提示消息(或天数)存入数组,通过月份直接索引数组,彻底消除大量分支,让代码更简洁高效。
优化后代码
.data msg_prompt: .asciiz "请输入月份:" # 按月份顺序存储对应的提示消息,索引0对应1月,索引11对应12月 msg_days: .asciiz "这个月有31天。\n" .asciiz "这个月有28/29天。\n" .asciiz "这个月有31天。\n" .asciiz "这个月有30天。\n" .asciiz "这个月有31天。\n" .asciiz "这个月有30天。\n" .asciiz "这个月有31天。\n" .asciiz "这个月有31天。\n" .asciiz "这个月有30天。\n" .asciiz "这个月有31天。\n" .asciiz "这个月有30天。\n" .asciiz "这个月有31天。\n" .text .globl main main: # 打印输入提示 li $v0, 4 la $a0, msg_prompt syscall # 读取用户输入的月份(1-12) li $v0, 5 syscall move $t0, $v0 # 转换为数组索引(0-11)并计算地址偏移:每个字符串地址占4字节,左移2位等价乘4 subi $t0, $t0, 1 sll $t0, $t0, 2 # 定位到对应月份的提示消息地址 la $t1, msg_days add $a0, $t1, $t0 # 打印结果 li $v0, 4 syscall # 退出程序 li $v0, 10 syscall
优化点说明
- 消除分支开销:用数组查表替代所有分支判断,直接通过月份索引定位结果,避免了分支预测的性能损耗
- 移除冗余逻辑:删掉原代码中无意义的数字输出,直接打印对应提示,代码更简洁
- 可读性提升:数组结构清晰,每个月份对应的消息一目了然,后续维护更方便
内容的提问来源于stack exchange,提问作者SteelBladee
相关产品推荐
相关产品推荐

