[stella] optimization

Subject: [stella] optimization
From: "Andrew Davie" <adavie@xxxxxxxxxxxxxxxxx>
Date: Wed, 13 May 1998 21:21:14 +1000
Here's a quickie... I always like a quickie....

When you need to multiply... think carefully about the binary organisation
of either of the numbers, and how you can use powers of two to make your job
qucker by incorporating shifts

A shift to the left is the same as multiplying by two

    lda n
    asl                ;  a now holds  2n

So, multiplying by powers of two is as simple as shifting multiple times....
this is pretty straightforward so far...

    lda n
    asl
    asl                ; a holds 4n


OK, easy stuff.  But what if we want to multiply by 3.  ... well, that's the
same as multiplying by two and adding the original

    lda n
    asl
    adc n             ; assuming n was < 127 originally, a holds 3n

See how I left out the carry before the add, on the assumption that it would
be cleared by the shift (asl) instruction before.  Mostly, you have a fair
idea of values you're working with, so can guarantee the validity of this.

So, x3 turns out to be pretty easy.  let's try x10
Welll... breaking it into blocks of multiplies by two (ie: shifts) is as
simple as looking at the binary bit pattern...  10decimal  is 1010binary.
That shows us that we need to shift once, then shift twice, then add the two
together.  Here we go...

    lda n
    asl
    sta temp            ; temp holds 2n
    asl
    asl                       ; a = 8n
    adc temp            ; +2n = 10n

OK, all assuming we won't have overflow - otherwise insert a carry before
the add.  But see how I've just done a x10 with just 15 cycles of processor
time, and 9 bytes!  Watch when you need to do multiplies just what values
you're dealing with - you could save yourself a lot of cycles :)

Always be prepared, though, to just whack in a huge table in ROM...

    ldx n
    lda times10,x

...

times10
    db 0,10,20,30,40.... etc

That only took 7 cycles, mmmh :)

I hope this stuff isn't too basic for the list, but hope some may be
interested.  If its too basic, let me know and I'll up a notch :)

Enjoy!
A


--
Archives (includes files) at http://www.biglist.com/lists/stella/archives/
Unsub & more at http://www.biglist.com/lists/stella/stella.html

Current Thread