【发布时间】:2013-10-24 19:50:14
【问题描述】:
要遍历一个数组,你会向左逻辑移动 2 次,还是每次将指向基地址的指针增加 4?首选方法是什么?有什么更好的方法?
【问题讨论】:
要遍历一个数组,你会向左逻辑移动 2 次,还是每次将指向基地址的指针增加 4?首选方法是什么?有什么更好的方法?
【问题讨论】:
假设您从 $t0 开始指向单词数组开头的内存位置:
.data
mywords: .word 0:100 # 100 words, initialized to 0x0
.text
la $t0, mywords
假设您从 $t0 中的一个值开始,我们不想转移,这里有一些替代方案:
sll方法
# $t0 points to base address, $t1 word counter initialized to zero
loop:
sll $t2, $t1, 2 # Turn word pointer into a byte pointer
add $t2, $t0, $t2 # Get pointer to the word we want
lw $s0, 0($t2) # Load the word into $s0
addi $t1, $t1, 1 # Point to next word
# (do something useful here)
j loop
添加方法,保留$t0
# $t0 points to base address, $t1 byte counter initialized to zero
loop:
add $t2, $t0, $t1 # Get pointer to the word we want
lw $s0, 0($t2) # Load the word into $s0
addi $t1, $t1, 4 # Point to next word
# (do something useful here)
j loop
添加方法,丢弃$t0
# $t0 points to base address
loop:
lw $s0, 0($t0) # Load the word into $s0
addi $t0, $t0, 4 # Point to next word
# (do something useful here)
j loop
我们只是在课后讨论,这些构建循环的方法中哪种更有效。我一直在使用sll 方法,因为我喜欢玩比特……但它看起来效率最低(通过一条指令)。
我想这将取决于您需要保留哪些变量。
sll 方法:$t0 告诉你从哪里开始,$t1 告诉你哪个词 你在,$t2 是从头开始的
添加方法 1:$t0 告诉你从哪里开始,$t1 告诉你哪个 字节你在,$t2 是从头开始
添加方法 2:不知道你在哪里,但它释放了 $t1 和 $t2
与往常一样,哪个“更好”取决于您的程序需求。
【讨论】:
$t0,请在循环外复制一次,而不是在内部浪费指令。所有这些循环都是无限的;通常你会使用bne $t0, $t1, loop 而不是j loop,$t1 是一个指向你之前在循环之外计算的结束的指针。喜欢Translating C function with args to MIPS: loop over an int array and count negatives