Skip to main content
GameDev.net gamedev.net
🔒 Locked

division

Started by JasonL220 May 26, 2006 at 7:26 AM 4 replies 400+ views
Original Post
JasonL220
JasonL220
i have seen that bit shifting can be done like this i >> 1 which is exfectively halfing the number, and drop any decimal points. i wondered if it is fast to do that than i/2 ?
Fred304
Fred304
Write code that people understand. If you want to divide by two, write i/2. If you want bitshifting (for example to construct a RGB565 from single bytes), express it through the >> operator. Let the compiler do the work of optimizing.

BTW this is not correct:
Quote:

effectively halfing the number, and drop any decimal points

What really happens is that the halfed number gets rounded down:

 3>>1 == floor( 1.5) ==  1-3>>1 == floor(-1.5) == -2

paic
paic
And let people decide what they want to use. You don't answer the question, and I must say that I'm also curious to know the difference between both
Maybe Visual can optimize division / multiplication by power of two by replacing them by bit shifting ?
taby
taby
If it's faster than x/2, I wonder if x*0.5 is as slow.
jpetrie
jpetrie
Depends on the type of x.

x / 2 and x * 0.5f might different operations, depending on the type of x.
They cannot neccessarily be used interchangeably with x >> 1, depending on the type of x.
Implicit conversions might happen, depending on the type of x.

In any case, these are micro optimizations. It is interesting to know the differences between them, true, but unless a profiler reveals you are spending a lot of time doing integer divisions, there's no need to use bitshifting to perform divisions when the more natural operator would suffice. Clear, easy to read code is in general better than "faster" (but not really appreciably faster) hard-to-understand code. It's trivial for a compiler to optimize division or multiplication by constant powers of two into shifts.
janta
janta
I'll say almost the sane thing as previous posters. I dont like bit shifting to replace integer division. To me it sounds like an old programmer trick which has no reason to be used any more, for I'm convinced that compilers optimize that pretty easily.

So personally I use "/2" :)

Bye bye !

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.