PocketMatrix forums

A read-only archive of the PocketMatrix forums (2001–2014). Posting and accounts are closed.

Recip/Divide routines.

I've noticed a few people stating that recip tables are faster than doing a divide. While I understand the obvious here, I would have thought that the cache hit would negate much of the advantage.

What size recip tables are people using? Is there a routine out there that uses a small recip table and then some code to get a high bit answer? We usually are looking for about 14->16 bits for the recip. ie;

long invW= ((1<<30)/w)<<2; //invW is 16:16
verts->x=imul16(verts->x*invW);
etc...

Actually, everthing is done is ASM to take advantage of the 32x32->64 bit multiply (and accumulate) functions of the ARM.... but you get the idea. ;)

Cheers,

rcp
bluescrn · 17 Jul 2003, 22:20 UTC — Recip/Divide routines.
My recommendation of reciprocal tables came from GBA programming experience, where cache isn't an issue... I've not spent much time on PocketPC 3D (yet), so I've not profiled anything yet...

For Super Monkey Ball Jr (GBA), we used a 32Kb table (16k entries) for the perspective divide ('perspective multiply'...). That was in ROM. For the DDA divides, we used a smaller table (500 entries?) in fast internal RAM (single cycle access)
a couple of days ago i exchanged some divides in my rasterizer with table lookups. The framerate went down 2-3 frames on the PPC and stayed the same on the PC. (using gapidraw for testing on both PPC and PC)

So now im back to doing divides :)

have fun,
I'd be real interested in hearing more about the smaller table. I think for this to be effective, you need a table that would fit in half the data cache, and then a supporting algorithm to carry out the recip.
rcp wrote:
I'd be real interested in hearing more about the smaller table. I think for this to be effective, you need a table that would fit in half the data cache, and then a supporting algorithm to carry out the recip.


My small table was nothing special - we just knew we only needed to divide by a small renge of values (Say 1-500, as polygons were never >500 pixels high). No sub-pixel accuracy there, though

However someone at work did write a divide routine that used a smallish table and had a big range/reasonable accuracy - shifting the values down until they fitted a 1K-entry recip table, using a "sort of logarithmic shifting algorithm" (according to his comments...) instead of sitting in a >>1 loop. I'm not sure how fast it was in practice - How many cycles does a cache miss actually cost on an average PocketPC?
Back in the days of my Acorn (ye olde ARM machines) programming, we always used look-up tables for division. Way back then a coder associate swore by the kind of logarithmic system that you mentioned... but I've never really had the maths to work out what exactly he was talking about (and searching online for hints gave me no real answers either). I too would be very interested in hearing more about it.
a simple use of logarithms in optimization is to make use of this property:

log(a*b) = log(a) + log(b)

That way, you can code a multiplication (or division using log(a) - log(b)) with 3 table lookups. One for log(a), one for log(b) and one to execute the exponential function.

The advantage of such a system is that you can lookup any multiplication between two integers between 0 and n with log tables that have only n entries.

cryo
bluescrn:
This sounds like what i am looking for. I'll have to give it some thought.

I have know idea what the cache miss is, other than that I had a height map routine that was "walking" out of the cache at times (certain rotation angles) and it was *10* times slower. I changed to a tile based texture system and everything was fine after that. I've never really paid that much attention to cache issues before, because, quite frankly, I've never seen a 10x impact before. Me thinks that the XScale 400MHz turns into a 5Mhz Z80 when it can't get to its memory. ;)

cryo:
Man, you just lost me in the dust there. I *think* I remember something like this from school way back when, but I am sure I just went out and had a beer instead of learning it. :)

Anyone out there happen to know how many cycles the c runtime divide is (32/32)?
Sergey Chaban · 21 Jul 2003, 00:40 UTC
This is very interesting thread.
The logarithm equation is true for base 2 logs as well.
And XScale is able to calculate (31-LOG2(x)) with a single instruction.
So here is some variation on the logarithmic theme (without lookup tables):

Code:

int arm_clz(int x) {
unsigned ux = (unsigned)x;
int res = (x >> 31);
if (res == 0) {
if (ux < (1 << 15)) {
ux <<= 16;
res += 16;
}
if (ux < (1 << 23)) {
ux <<= 8;
res += 8;
}
if (ux < (1 << 27)) {
ux <<= 4;
res += 4;
}
if (ux < (1 << 29)) {
ux <<= 2;
res += 2;
}
if (ux < (1 << 30)) {
ux <<= 1;
res += 1;
}
}
return (res+1);
}

//#define XSCALE_BUILD
//#define HAVE_CLZ_INTRINSIC
#if defined(XSCALE_BUILD) && defined(HAVE_CLZ_INTRINSIC)
#define _CLZ(_x) _CountLeadingZeros(_x)
#else
#define _CLZ(_x) arm_clz(_x)
#endif

unsigned _udiv(unsigned a, unsigned b) {
int bitcount = _CLZ(b) - _CLZ(a);
unsigned res = 0;
if (bitcount >= 0) {
b <<= bitcount;
do {
if (a >= b) {
a -= b;
res |= 1;
}
--bitcount;
if (bitcount >= 0) {
res <<= 1;
b >>= 1;
}
} while (bitcount >= 0);
}
return res;
}


This code will support SA by default (with ARM-friendly CLZ routine), define HAVE_CLZ_INTRINSIC and XSCALE_BUILT to make use of CLZ instr if you have Intel compiler for XScale or compiling with newer MS compiler for PPC2003.
That's for unsigned division only, adding support for sign bit is trivial.
This code is generally faster than runtime division routine, that is OEM routine in coredll. Intel compiler uses its own (faster) math routines.
However there is even faster way to divide two fixed-point numbers 8)
Sergey Chaban wrote:
This is very interesting thread.
The logarithm equation is true for base 2 logs as well.
And XScale is able to calculate (31-LOG2(x)) with a single instruction.
So here is some variation on the logarithmic theme (without lookup tables):

<snip>

This code is generally faster than runtime division routine, that is OEM routine in coredll. Intel compiler uses its own (faster) math routines.
However there is even faster way to divide two fixed-point numbers 8)


OK, thanks, this makes a lot of sense to me now. I think in code, so having an answer in code works for me.

BTW, you say there is an "even faster way to divide two fixed-point numbers".. well, please, please do tell. ;)

Cheers,

rcp
I have know idea what the cache miss is, other than that I had a height map routine that was "walking" out of the cache at times (certain rotation angles) and it was *10* times slower.


We used to get around that one by holding two versions of the heightmap. One "normal" one and one rotated. When you do the traversal, you use the one which is most cache-aligned. It's more memory intensive, but faster for the "worst" case, giving a better average. It certainly worked ok for a small data-set.

Me thinks that the XScale 400MHz turns into a 5Mhz Z80 when it can't get to its memory.


You should see how fast they go when you turn off the cache. In some cases, my ancient 8MHz ARM 2 (no cache, no pipeline) used to *beat* a 200MHz StrongARM with its cache(s) turned off. The XScale should suffer even worse, in theory. Deep pipelines and no cache really don't mix.
Sergey Chaban · 21 Jul 2003, 13:09 UTC
rcp wrote:
BTW, you say there is an "even faster way to divide two fixed-point numbers".. well, please, please do tell. ;)


OK, here it is. This is _unoptimized_ version.
This code calculates 1/x in 16.16 fixed point, where x is a 32-bit integer,
i.e. recip_approx(2) == 0x00008000;
To make it really efficient: replace floats with 0.32 fixed-point, utilize 32*32=64 mul instruction on ARM, optimize polynomial evaluation as described in the "Numerical Recipes in C", on XScale make use of CLZ.

Code:

#define MKFP32(_x) (__int64(_x) << 32)

long recip_approx(long n) {
int lzn = _CLZ(n);
int sh = 31 - lzn;
float x = ((unsigned)n << (lzn+1)) / (float)MKFP32(1);
bool adj = (x >= 0.5f);
if (adj) {
x = ((unsigned)n << (lzn+2)) / (float)MKFP32(3);
--sh;
}
x = 1.0f - x + x*x - x*x*x + x*x*x*x - x*x*x*x*x + x*x*x*x*x*x -
x*x*x*x*x*x*x + x*x*x*x*x*x*x*x - x*x*x*x*x*x*x*x*x;
x *= (1 << 16);
if (adj) x = x/3;
return ((long)x >> sh);
}


Have fun,
SC
I dug up some interesting links:

<a href="http://citeseer.nj.nec.com/alverson91integer.html">Integer Division Using Reciprocals (1991)</a>

A discussion of ARM division routines (again harking back to my Acorn days), <a href="http://www.poppyfields.net/acorn/tech/division.shtml">here</a>
refractor wrote:
I dug up some interesting links:

<a href="http://citeseer.nj.nec.com/alverson91integer.html">Integer Division Using Reciprocals (1991)</a>

A discussion of ARM division routines (again harking back to my Acorn days), <a href="http://www.poppyfields.net/acorn/tech/division.shtml">here</a>


cool, this is very similar to how floating point division is done on many DSPs. ie; a lookup table to get close and then some multiplies to get the exact recip and finish the "division".

Between this and Sergey's contribution, I am pretty sure that there is a much faster method of division.

I'll work this out over the next week or so and post my results.

Cheers,

rcp
Sergey Chaban":2l8xde0o]


thanks a TON for posting this code. I can't wait to get at it.

Cheers,

rcp
refractor:

After reading this article again, I realized that what they are doing *is* floating point. They convert the integer to floating point, use part of the mantissa as a lookup for the recip and then proceed from there. This is how most DSPs do their floating point division and it works great. However, converting the integer to floating point (normalizing it) is not exactly quick.

Amazingly, it seems that Tera is no more. I was hoping to contact the author to see if they had looked at other normalization methods.

Oh well... I guess I'll try to come up with a fast normalization technique and give this a try.

Thanks again for posting the link.

Cheers,

rcp
I think (as you also implied) that normalisation will cost you more than it's worth.

More digging:

<a href="http://groups.google.com/groups?hl=en&lr;=&ie;=UTF-8&frame;=right&th;=d2f2d9faf640ca79&seekm;=28eb7f5.0203251520.7fb8f246%40posting.google.com#link1">Discussion about division</a> in comp.sys.arm

If I get time this evening, I'll crank up my "old" StrongARM machine and do some speed tests between the versions I've found so far. The accuracy test(s) will have to probably have to wait.
refractor:

Thanks for the link, it looks like a winner. I look forward to seeing your results. I am going to try and couple of things tonight, and I'll let you know.

Cheers,

jb
I didn't get time last night :(. I'm going to try and patch stuff together during the day today and test it tonight.
rcp · 24 Jul 2003, 08:49 UTC — first test
refractor:

I combined one of the algorithms from the Acorn info you provided and one from one of my DSP app notes. The resulting algorithm is shown below... first in C, and then in ASM.

Test conditions: I had my 3D game process each group of vertices 100 times. While there is still a lot of other processing that happens (ie; texture mapping and such), repeating the processing 100 times at least puts some focus on the divide routine.

The original divide routine was defined as such:
Code:

inline long idiv16(long x, long y)
{
__int64 z=((__int64)x<<16)/y;
return((long)z);
}


I've named the new routine, "nr-mod" as it is a modified (sort of unrolled) Newton-Raphson approach.

Code:

// long results=idiv16(long numerator,long denominator);
// assumes numerator, denominator are 16:16
// results is 16:16

inline long idiv16(long n,long d)
{
long g,t0,t1,t2;
long sign=d&0x80000000;
if(sign)
d=-d;

//we need a good guess to start the Newton-Raphson interation
//the logic that follows is from a suggestion by David Seal (dseal@acorn.co.uk) found at:
//http://www.poppyfields.net/acorn/tech/division.shtml (toward the bottom)

g=3;
long td=d;
while((td&0x40000000)==0)
{
td<<=1;
g<<=1;
}

//now we have our guess for the modified Newton-Raphson iteration
//the following iterative convergence algorithm is from:
//Cavanagh, J. 1984. Digital Computer Arithmetic. McGraw-Hill. Page 284.

t1=imul16(g,d); //t1=g*d
t2=imul16(g,n); //t2=g*n
t0=0x20000-t1; //t0=2-t1

t1=imul16(t0,t1); //t1=(2-(g*d))*(g*d)
t2=imul16(t0,t2); //t2=(2-(g*d))*(g*n)
t0=0x20000-t1; //t0=2-((2-(g*d))*(g*d))

t1=imul16(t0,t1); //t1=(2-((2-(g*d))*(g*d)))*(2-(g*d))*(g*d)
t2=imul16(t0,t2); //t2=(2-((2-(g*d))*(g*d)))*(2-(g*d))*(g*n)
t0=0x20000-t1; //t0=2-((2-((2-(g*d))*(g*d)))*(2-(g*d))*(g*d))

t0=imul16(t0,t2); //t0=(2-((2-((2-(g*d))*(g*d)))*(2-(g*d))*(g*d)))*
// (2-((2-(g*d))*(g*d)))*(2-(g*d))*(g*n)
if(sign)
t0=-t0;
return(t0);
}


I didn't bother optimizing the C routine, as I will use the ASM version on the PPC. I just needed the C routine for running on the PC. Here is the ASM routine. Note, it assumes XScale, and the latest version of ARMASM. If you don't have the latest ARMASM, (but do have an XScale) then put DCD 0xE16F3F11 in place of the clz instruction. If you don't have an XScale, you need to put some code there to count the leading zeros.

Code:

;// idiv16
;//
;// long results=idiv16(long numerator,long denominator);
;// assumes numerator, denominator are 16:16
;// results is 16:16

;// register definitions

numerator RN 0
denominator RN 1
guess RN 2
t0 RN 0
t1 RN 1
t2 RN 3
n0 RN 6
n1 RN 7
sign RN 4
fix2 RN 5


PROC

stmdb sp!, {r4 - r7, lr} ;// save r4-r7, return address

movs sign,denominator ;// copy denominator to sign updating flags, N flag well be set if negative
mvnmi denominator,denominator ;// if MI (negative), take one's complement
addmi denominator,denominator,#1 ;// if MI (negative), add one to get two's complement

;//we need a good guess to start the Newton-Raphson interation
;//the logic that follows is from a suggestion by David Seal (dseal@acorn.co.uk) found at:
;//http://www.poppyfields.net/acorn/tech/division.shtml (toward the bottom)

mov guess,#3 ;// initial guess, two LSB
clz t2,denominator ;// find most significant bit
sub t2,t2,#1 ;// we shift the guess up by one less than the number of leading zeros, so dec the count
mov guess,guess,lsl t2 ;// shift guess up

;//now we have our guess for the modified Newton-Raphson iteration
;//the following interative convergence algorithm is from:
;//Cavanagh, J. 1984. Digital Computer Arithmetic. McGraw-Hill. Page 284.

smull t2,n1,guess,numerator
smull t1,n0,guess,denominator
mov fix2,#0x20000 ;// setup a constant to subtract off (done here to eat up some of the multiply delay)
mov t2,t2,lsr #16 ;// shift low 32 bits of results down 16
orr t2,t2,n1,lsl #16 ;// shift high 32 bits up 16 and or in with low, equiv to c=(long)(((__int64)a*(__int64)b)>>16);
;// t2=guess*numerator
mov t1,t1,lsr #16
orr t1,t1,n0,lsl #16 ;// t1=guess*denominator
sub t0,fix2,t1 ;// t0=0x20000-t1

smull t1,n0,t0,t1 ;// repeat above
smull t2,n1,t0,t2
mov t1,t1,lsr #16
orr t1,t1,n0,lsl #16
sub t0,fix2,t1
mov t2,t2,lsr #16
orr t2,t2,n1,lsl #16

smull t1,n0,t0,t1 ;// repeat above
smull t2,n1,t0,t2
mov t1,t1,lsr #16
orr t1,t1,n0,lsl #16
sub t0,fix2,t1
mov t2,t2,lsr #16
orr t2,t2,n1,lsl #16

smull t0,n0,t0,t2 ;// last step
mov t0,t0,lsr #16
orr t0,t0,n0,lsl #16

movs sign,sign ;// copy sign whilst updating flags, N flags well be set if negative
mvnmi t0,t0 ;// if MI (negative) take one's complement
addmi t0,t0,#1 ;// if MI (negative) add one to get two's complement


ldmia sp!, {r4 - r7, pc} ;// restore r4-r7 and return

ENDP



With this routine being called throughout my game, I noticed no difference in rendering accuracy, so I am assuming that the routine is doing a pretty good job. Maybe someone else can test the accuracy. Here are the results:

Dell Axim @ 200MHz
----------------------
original: 2.6 fps
nr-mod in C: 3.5 fps
nr-mod in ASM: 4.0 fps

Dell Axim @ 400MHz
----------------------
orginal: 5.2 fps
nr-mod in C: 6.8 fps
nr-mod in ASM: 7.3 fps

Obviously, the nr-mod routine is a good bit faster than the C LIB routine. I was a little surprised that the ASM routine was not that much faster than the C routine. I guess I need to go back over the ASM routine and see if I missed something.

It is important to note that these results are from a game, one that is completely filling the screen with textured polys, lightmaps, dynamic lighting, playing MP3 and what not. There are *not* many divide routines relative to the rest of the code. Thus the increase in fps is quite amazing. I will probably write a simple test program that focuses only on the divide routine.

Note that at 400MHz, the nr-mod (ASM) routine is starting to fall off a little bit. It is not twice the fps as when running at 200MHz. This is very typical of the XScale as it is starting to outrun memory. Note to Intel... most program do need to access memory, so that should be fast. ;)

It would be great if others could take this routine, try it out, optimize it some more and post their results.

Have fun!

rcp
Hi there. Thanks for the nice post. :)

Right, comments:


  • Code:
    mvnmi denominator,denominator ;// if MI (negative), take one's complement
    addmi denominator,denominator,#1 ;// if MI (negative), add one to get two's complement

    ==
    Code:
    rsbmi denominator, denominator,#0


    (Same goes for the "movs sign,sign" final part).

  • Also,
    Code:
    "sub t0,fix2,t1"
    x 3 can be rearranged to
    Code:

    rsb t0,t1,#0x20000

    , saving you using/stacking a register (fix2).

  • The sign register... it's a dirty hack, but you don't need to store the sign in a register in this case - none of the instructions in your routine should mess with the processor's flags (well actually the SMULL will on ARM v4 architectures (StrongARM), but as XScale is V5 you're alright).

  • Being really picky, but when using the stack, you should use "ldmfd" rather than "ldmia" (they are the same instruction, but the connoitation is better with ldmfd I think).


I'll have a proper poke later. I don't seem to have much free time to do "interesting" stuff right now. <Sigh> :(
refractor:

great stuff man, thanks!

Something else I forgot to mention is that in a lot of typical situations (perspective divide, for example) you really want this routine to get the recip and multiply out several numbers. Thus in addition to the idiv routine you would probably want things like;

Code:


long wNormalize(long w,long *x,long *y,long *z); //preforms homogeneous normalization of x,y and z, returns 1/w



etc. etc.

In the wNormalize(4P) routine you would calculate the recip as previous, but also divide out x,y,z at the same time. This would be a little faster than taking the recip and multipling. ie; 1 function call vs. 4.

BTW, going out of town and I am unsure of my connectivity where I am going... so I may not be "back" until Sunday.
refractor:

thanks for the tips, i managed to eek a little more performance out of the routine. I did a test that only focused on the idiv16() routine. I did 50K divides in a loop, storing the results in a 256 byte array, overwritting as required. Here are the results:

standard 'C' division: 450K divides per second
nr_mod in ASM: 2,100K divides per second

With very little overhead the real speed of the nr_mod routine is more visible. This routine is 4.6 times faster than the 64 bit divide in the C library.

I probably am going to take some time to rework my math libary to look for other instances where this technique will work. Normalizing vectors, distances and other similar routines should benefit greatly as well.

Hopefully you can get some time to run some tests. It would be great if we could somehow get another 2x increase in the nr_mod technique.
The nr_mod function is amazing but it seems that it is a bit less accurate than it's 64bit divide counterpart, isn't it?
Using it in my texture-mapper brought some glitches in but nevertheless it's so much faster :) You saved my life, i was so desperately looking for a fast fixed-point divide!
You should be able to iterate one more time and fix any accuracy problems. I (and I am sure many others) will be testing the accuracy more in the future. In addition to doing more iterations, you can also increase the accuracy of the "guess" and thus reduce the needed iterations. Note that you can also iterate until you are happy with the accuracy. For more detail on that, check out the earlier link that refractor posted.
Thanks for the tip, and yes one more iteration step solves most of the "perspective"-glitches that occured, but hey for the sake of speed i'm willing to accept those minor glitches (happened only when getting real close to polygons which should not be the case in a final product :) )
While I'm at it, I'll revive another old thread :). I tried the nr-mod division you put out rcp, and you just increased my framerate by 4fps on a 500 poly flat-shaded one light source object on my Audiovox Maestro (now at 31fps). Thanks! :) However, I'm using the C routine, as I don't have the CLZ instruction.

I'm wondering if anybody has come up with a reasonably fast ASM CLZ routine for non-XScale processsors? Can't seem to find anything here and it would probably be pretty useful. I've outputted a arm_clz() C-routine to ARM assembly that I found here, but its pretty long and looks pretty unoptimized. I guess I could learn something and do it myself, but I'm feeling lazy on something so trivial :).

Chris
Too lazy to even search this forum? :P

http://www.pocketmatrix.com/forums/view ... hlight=clz

If not, comp.sys.arm would have also be a good place to look :P :
http://groups.google.com/groups?hl=en&l ... eros%2Barm

:mrgreen:
refractor wrote:
Too lazy to even search this forum? :P

http://www.pocketmatrix.com/forums/view ... hlight=clz

If not, comp.sys.arm would have also be a good place to look :P :
http://groups.google.com/groups?hl=en&l ... eros%2Barm

:mrgreen:


Heh, Kind of. I'm hoping for ASM, but thats probably asking too much :). Could somebody help me out with this much? - I was playing around with taking the .asm file output of a CLZ function written in C. If I give this a label of _clz or something, and have it return the result in R0, how would I call it in place of rcp's explicit call to the CLZ instruction? Put the value in R1, and do a branch?

Chris
Blah, you know what? Nobody answer the above. I dont need everything handed to me on a silver platter :). There are enough links in the ASM FAQ sticky for me to figure it out.

Chris
Just to hint that you should add the CLZ assembler you write in-line into the divide routine - don't branch to another function in there or you'll kill its performance.
refractor wrote:
Just to hint that you should add the CLZ assembler you write in-line into the divide routine - don't branch to another function in there or you'll kill its performance.


Thanks, yeah, I was planning on doing that. But I know very little about StrongARM assembly, so I was going do it as a function first, then inline. Baby steps for me :).

Chris
Sergey Chaban · 18 Nov 2003, 16:46 UTC
I'm using the following macro for CLZ on SA, it's the same as C version I've posted earlier in this thread:

Code:

MACRO
ARM_CLZ $r0, $r1
mov $r0, #0
cmp $r1, #(1:SHL:15)
addlo $r0, $r0, #16
movlo $r1, $r1, lsl #16
cmp $r1, #(1:SHL:23)
addlo $r0, $r0, #8
movlo $r1, $r1, lsl #8
cmp $r1, #(1:SHL:27)
addlo $r0, $r0, #4
movlo $r1, $r1, lsl #4
cmp $r1, #(1:SHL:29)
addlo $r0, $r0, #2
movlo $r1, $r1, lsl #2
cmp $r1, #(1:SHL:30)
addlo $r0, $r0, #1
cmp $r1, #0
addge r0, r0, #1
MEND

EXPORT arm_clz

; int arm_clz(int x);
arm_clz
mov r1, r0
ARM_CLZ r0, r1
mov pc, lr


SC
To all...

I will be releasing a beta for my game soon. If that goes well then the game will be released and I plan on dedicating a bit of time to fast math routines. The divide/recip will be the first I tackle. I have improved the accuracy of the version that I posted and it is still about the same speed. When I get some free time, I will post it. I am also looking more at combining the divide into the rest of the normal operations to save some overhead. I'll post more info when I get to it if people are still interested.

Cheers,

rcp
has anybody compared these routines to those the intel GPP provides (in terms of code and performance)?

thx,
DANIEL
Sergey Chaban wrote:
I'm using the following macro for CLZ on SA, it's the same as C version I've posted earlier in this thread:


Sergey, line 19 should read:

addge $r0, $r0, #1

It will work as-is using your function wrapper, but not if you use the macro directly and pass $r0 as something other than r0. Refractor caught that one. It was driving me crazy trying to find that bug. :)

Also (this is stating the obvious) but the macro will trash $r1, so save that register before you call the macro if you need the value later. It is not a drop-in replacement to clz for that reason.

BTW, thanks for posting this routine. It really works well. Rcp, same with the idiv16. I'll post some benchmarks here shortly.

Dan East