Public Group

how to optimize the following code?

This topic is 2904 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;

also following your logic

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:
 Original post by EvilNandowhat about this ? int a = b % 1;
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.

• 39
• 12
• 10
• 10
• 9
• Forum Statistics

• Total Topics
631367
• Total Posts
2999592
×