Click here to Skip to main content
15,867,686 members
Please Sign up or sign in to vote.
5.00/5 (2 votes)
When performing division by a constant that is a multiple of 2 we can optimise the operation by performing a right shift.

eg

i = i >> 3;

is equivalent to

i = i / 8;

My questions are:

* Is there likely to be a tangible benefit to doing this or would a compiler (gcc in my case) make this optimisation?

* Is it possible to perform a similar optimisation to the modulus operation when working with a known value that is a multiple of 2?
Posted
Updated 28-Apr-10 2:31am
v2

When you write bitwise shift operation equivalent microoperation takes only one micro-operation to be performed by the ALU(CPU). It takes binary representation of the value supplied and performs a single "shift" micro operation.

But when you write a division(float) it is converted into either a single "shift" micro operation or multiple micro opearation depending upon the kind of CPU in use and its instruction set. Hence likely to take more time.

With the latest advance CPU where all floating point/interger division ( along with all other data type operation ) "hardwired" , the time gain doing the first operation is almost neglegible.

I would like to get to see what others say in this regard. I read all this long back(in college days :-D ), so apologise if I have made a wrong word un-intentionally.
 
Share this answer
 
Josh Gray wrote:
* Is there likely to be a tangible benefit to doing this or would a compiler (gcc in my case) make this optimisation?

VC++ compiler takes care of such optimization (I see no div operation).
I guess gcc do the same, you may verify it using the -S switch and looking at the assembly file produced.

Josh Gray wrote:
* Is it possible to perform a similar optimisation to the modulus operation when working with a known value that is a multiple of 2?

Yes, for instance
i = i & 7;

is equivalent to
i = i % 8;

for positive values of i (an advantage of letting the compiler optimize for you, is the automatically handling of the negative numbers too).

[added]
I assume integer operation, of course.
[/added]

:)
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900