Public Group

# how to optimize the following code?

This topic is 3077 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

int a = b * 4;

lol silly but actually i saw this at an exam and I was curious

##### Share on other sites
a = b << 2;

##### Share on other sites
and the reasoning behind this is?

##### Share on other sites
x * 2 == x << 1 //shifting by 1 yield the same as multiplying by 2
x * 4 = x * 2 * 2 = (x << 1)* 2 = ((x << 1) << 1) = x << 2

##### Share on other sites
Doesn't the compiler do this optimization automatically?

##### Share on other sites
int a = b % 1;

int a = (b + c) / 2;

should be

int a = (b + c) >> 1; ??

thanks

##### Share on other sites
Quote:
 Doesn't the compiler do this optimization automatically?

It very well could. And You might want to leave it to the compiler to figure this out anyway, if only because it is a micro-optimization that clutters up your code.

int datacount = input << 2;
takes longer for a person to parse than
int datacount = input * 4;

Quote:
 int a = b % 1;

Think logical bit operations aswell.

Again, it probably isn't worth optimizing till it is actually a problem.

Quote:
 int a = (b + c) >> 1; ??

Yes.

##### Share on other sites
Yup, at least g++ does have quite decent optimizations for this.

Dividing by multiplying -> shows some x/13 is compiled into a multiplication and a right shift

And (plug plug) here are some more examples, and BubuLV has some more and a pointer to Division by Invariant Integers using Multiplication.

Rule of thumb: Do not micro-optimize. A good compiler will do it for you already.

##### Share on other sites
Quote:
The remainder when dividing by one?
Well that's simply a long way of writing:
int a = 0;

##### Share on other sites

int a = (b + c) / 2;
should be
int a = (b + c) >> 1; ??

yea, but remember, that the shift operator works on integral types, so b and
c has to be correctly defined.

1. 1
2. 2
3. 3
Rutin
28
4. 4
khawk
14
5. 5

• 11
• 11
• 23
• 10
• 9
• ### Forum Statistics

• Total Topics
633648
• Total Posts
3013111
×