25.12.2012 Views

MIPS Assembly Language Programming

MIPS Assembly Language Programming

MIPS Assembly Language Programming

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

48 CHAPTER 3. ADVANCED <strong>MIPS</strong> TUTORIAL<br />

sw $t1, 16($sp) # save $t1.<br />

sub $a0, $t0, 2 # compute fib (n - 2)<br />

jal fib<br />

move $t2, $v0 # $t2 = fib (n - 2)<br />

lw $t0, 20($sp) # restore n.<br />

lw $t1, 16($sp) # restore $t1.<br />

add $v0, $t1, $t2 # $v0 = fib (n - 1) + fib (n - 2).<br />

b fib_return<br />

fib_base_case: # in the base case, return 1.<br />

li $v0, 1<br />

fib_return:<br />

lw $ra, 28($sp) # Restore the Return Address.<br />

lw $fp, 24($sp) # restore the Frame Pointer.<br />

addu $sp, $sp, 32 # restore the Stack Pointer.<br />

jr $ra # return.<br />

Once again, we can time the execution of this program in order to see if this<br />

change has made any improvement:<br />

% echo 20 | /bin/time spim -file fib-t.asm<br />

SPIM Version 5.4 of Jan. 17, 1994<br />

Copyright 1990-1994 by James R. Larus (larus@cs.wisc.edu).<br />

All Rights Reserved.<br />

See the file README a full copyright notice.<br />

Loaded: /home/usr6/cs51/de51/SPIM/lib/trap.handler<br />

10946<br />

4.5 real 4.1 user 0.1 sys<br />

In these tests, the user time is what we want to measure, and as we can see,<br />

fib-s.asm is approximately 17% slower than fib-t.asm.<br />

3.1.1.3 Optimization: fib-o.asm<br />

Warning! Hacks ahead! There are still more tricks we can try in order to increase the<br />

performance of this program. Of course, the best way to increase the performance of<br />

this program would be to use a better algorithm, but for now we’ll concentrate on<br />

optimizing our assembly implementation of the algorithm we’ve been using.<br />

Starting with the observation that about half the calls to fib have an argument n<br />

of 1 or 0, and therefore do not need to do anything except return a 1, we can simplify<br />

the program considerably: this base case doesn’t require building a stack frame, or

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!