Subj : Re: faster approach to division To : comp.programming From : Gerry Quinn Date : Tue Jul 12 2005 11:17 am In article <9JyAe.351$Rv7.249@newssvr21.news.prodigy.com>, not@my.real.email says... > I'm working on a problem which involves a fair amount of integer > division but in essentially all cases the divisor is +/- 1 or +/- 2. > I'm using C++ and trying to figure out whether I should code this as > just ordinary division or whether it makes sense to create a special > class (basically a wrapped enumeration) to hold my possible divisor > values. Then I would overload operator/() to recast division as a null > operation or a sign flip and/or right shift. > > Anyone have any intuition on this? I've tried a few very simple tests > comparing division and shifting and it's hard to discern a difference, > but I'm not sure my tests are very effective. (Are modern machines > optimized to divide by 1 and 2 quickly?) If you want to do this, I suspect a wrapped enumerator may be the wrong way to go about it. Even leaving aside aliasing issues, you could end up with several tests (bad on modern processors). You could do two tests, or perhaps use a function pointer to jump to code for each case. In assembly, you might be able to come up with somethinmg reasonably short that has no branches at all. Possibly good if you are doing this repeatedly on a CPU with a very long pipeline. However, chances are that it will all be a waste of your time, which is more valuable than the CPU's! You've found this yourself, perhaps. If the program runs too slow, fix it. Otherwise, forget this and work on something relevant. - Gerry Quinn .