one line code

Started by
5 comments, last by SnotBob 15 years, 11 months ago
Guys, look at this line of code. Can it to be make more optimization?

int a;
(a/4)%16;

All i can think is to use bit operator like this: (a>>2)^4; Is this correct?
/*----------------------------------------------------------------------------------------------------------------------------------*/Enthusiastic and wild about game development. Any opportunity would get me sink into any fantastic game-revolution era.
Advertisement
^ is xor
what you want is (a>>2)&0xf
Quote:Original post by daviddiligent
Guys, look at this line of code. Can it to be make more optimization?

*** Source Snippet Removed ***

All i can think is to use bit operator like this:
(a>>2)^4;

Is this correct?
No. The compiler will do that for you - that's it's job. All you're doing by doing it yourself is making the code harder to read and maintain - as you've shown by using the wrong operator.
I'd not do such a thing any more these days, unless there is a very good reason for it. It makes your code more error-prone and less intellegible, and it doesn't buy you anything. Not one CPU cycle.
If such an optimization is legal, the compiler will do it anyway. However, the compiler will always do it right.
Replacing a modulus with a bitwise and won't do the same thing for signed integers. Feed -29 into the original formula and you get -7 back. The "equivalent" formula with a bitwise and will return 8 on a machine with two's complement negative integers.
Yes:
{}


- a is declared, but not initialized
- (a/4)%16; is calculated, but result is undefined (see above) and not even stored
- both lines of code aren't used anywhere

Hence, removing this code entirely is best optimization. There's no even a need for a NOP.


However - if you show how this fragment fits into the context of algorithm and data structures, or if you explain what you're trying to do, then I'm sure that we'll be able to find an algorithm which may solve your current performance problems.

I just tried this with GCC -O2 on x86:
int opt1(int a){	return (a/4)%16;}unsigned int opt2(unsigned int a){	return (a/4)%16;}int opt3(int a){	return (a>>2)&0xf;}

I won't bother posting the assembly. The two latter functions were almost identical, with the only exception being shrl vs. sarl. The first, however, produced a lot more code, but avoids the division. That code is actually rather surprising.

So if you happen to know that you only have non-negative values and can't use unsigned int for some reason, writing (a>>2)&0xf will produce slightly faster code, but probably not worth it.

This topic is closed to new replies.

Advertisement