Casper
Casper

Reputation: 1723

Optimization for MIPS sum array

I have some codes to sum array 50 times. Now I'm asked to reduce this code by at least 1 instructions. All I could think of was to increase this loop to 100 times and then add one element per loop. But this would increase the instruction counts a lot.

      addi $t1, $0, 50 
LOOP: lw $s1, 0($s0) 
      add $s2, $s2, $s1 
      lw $s1, 4($s0) 
      add $s2, $s2, $s1 
      addi $s0, $s0, 8 
      subi $t1, $t1, 1 
      bne $t1, $0, LOOP

Note that you can only rewrite this code, not write another sumArray algorithm

Upvotes: 0

Views: 451

Answers (1)

Michael
Michael

Reputation: 58447

This is one instruction less, by "combining" the address and the loop counter, thereby summing the array backwards:

      addi $t1, $s0, 400   # $t1 = $s0 + 50*2*sizeof(word)
LOOP: lw $s1, -4($t1) 
      add $s2, $s2, $s1 
      lw $s1, -8($t1) 
      add $s2, $s2, $s1 
      sub $t1, $t1, 8 
      bne $t1, $s0, LOOP

Upvotes: 1

Related Questions