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.

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

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

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

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

jr $ra # return.<br />

Let’s time this and see how it compares:<br />

% echo 20 | /bin/time spim -file fib-o.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 />

3.1 real 2.8 user 0.2 sys<br />

This is clearly much faster. In fact, it’s nearly twice as fast as the original<br />

fib-s.asm. This makes sense, since we have eliminated building and destroying<br />

about half of the stack frames, and a large percentage of the fib function does nothing<br />

but set up and dismantle the stack frame.<br />

Note that the reason that optimizing the base case of the recursion helps so much<br />

with this algorithm is because it occurs about half of the time– but this is not characteristic<br />

of all recursive algorithms. For example, in a recursive algorithm to compute<br />

the factorial of n, the recursive case will occur about n − 1 times, while the base case<br />

will only occur once. Therefore, it makes more sense to optimize the recursive case<br />

in that situation.<br />

There’s still more that can be done, however; see exercise 3.3.3 to pursue this<br />

farther. A complete listing of a program that uses this implementation of the fib<br />

function can be found in section 5.8 (on page 84).<br />

3.2 Structures and sbrk: the treesort Program<br />

Included in section 5.9 of this document is the source code for a SPIM program that<br />

reads a list of numbers from the user and prints out the list in ascending order. The<br />

input is read one number per line, using the read_int syscall, until the user types in<br />

the sentinel value. The sentinel value is currently 0, but can be changed in the code<br />

to any 32-bit integer.<br />

The treesort algorithm should be familiar to anyone who has used ordered binary<br />

trees. The general algorithm is shown in 3.1.

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

Saved successfully!

Ooh no, something went wrong!