Click to See Complete Forum and Search --> : integer divide - round up


Strogian
05-01-2004, 09:10 PM
I've got two options here:

#define hdiv(x,div) ((x-1+div)/div) /* x,div both integer types */
#define hdiv(x,div) (x/div + (x%div ? 1 : 0))

Which one is better? Or is there something even better than I haven't thought of?

I like the second one because it doesn't need the comment. It also is actually a bit easier to understand, I think.

first one: add, subtract, integer divide
second one: integer divide, cmp, jmp, mov, add? or div, cmp, jmp, add? something like that..

i'd say the first one is better directly...

then again, I don't know what it would get optimized into. It's pretty complicated. :D

bwkaz
05-01-2004, 09:55 PM
Generally the compiler is pretty good at optimizing, especially with -O3 (and sometimes some of the -fcrazy-batstuff (to paraphrase one of the LFS developers ;)) flags help a bit more).

I suppose you could compile with -S, and look at the resulting assembly output (that is, if you know AT&T assembler syntax), to see what gcc optimizes it to exactly. Or you could just trust it... ;)

Strogian
05-02-2004, 12:58 AM
Well, looking at the assembler output, it looked like the first one was better with no optimization, but as I upped it (to -O1, -O2, -O3, or -Os), the second one ended up with fewer instructions than the first. But when I finish the compile and do test runs, it turns out that the first one is better than the second, both in time and space taken up.

With no optimization, it's about twice as fast as the second one, and 22 bytes less. But with any optimization, it's only saving 2 bytes, and only shaves a tiny bit of time off. (probably around 1% or less)

Oh, I know why that second one is so bad with no optimization. It actually does the divide twice! I would never have imagined that. :) I guess that's the main thing that happens to #2 when I turn optimizations on.

bwkaz
05-02-2004, 01:42 PM
Oh, yeah, it would have to do the divide twice. Once to do the divide, and once to find the remainder. ;)

RhysU
04-01-2011, 11:51 AM
Would
#define hdiv(x,div) (((x+div)-1)/div) /* x,div both integer types */
be better as it is less likely to underflow unsigned types?

- Rhys