For example,
Let's say a variable x
,
x
could be anything include 0
.
Then we got code like:
if(x==0){
y = 1;
}
else {
y = x;
}
Could I do this without producing branches in C/C ?
I'm trying to optimize a piece of code. I want to remove branches as much as possible. There are similar judgments, so I want to convert them into statements without branches to make the code as efficient as possible.
CodePudding user response:
Some general notes:
- As mentioned in other comments, some compilers can optimize and eliminate the branch. You can check the assembly output (e.g. in Godbolt) to make sure.
- Beware of premature optimizations.
- Always measure and make sure your speculation about what's taking up time is correct.
Having said that you can try the following "trick":
y = !x x;
Assuming x
,y
are integer types:
If x==0
, !x
will be 1
and y
will be assigned to 1
.
If x!=0
, !x
will be 0
and y
will be assigned to x
.
Note: see @CostantinoGrana's comment below about the guarantee in the standard. You can also verify it in your specific environment (compiler etc.).
CodePudding user response:
You should check the assembler output of your compiler. For example,the X86 architecture has an instruction called cmov (https://www.felixcloutier.com/x86/cmovcc) that is designed to handle this kind of thing without branches. The Arm architecture allows pretty much all instructions to be executed depending on CPU flags: https://developer.arm.com/documentation/dui0473/m/condition-codes/conditional-execution-in-arm-state.
Thus, when optimizations are enabled your compiler will likely produce no branches.
CodePudding user response:
Maybe you can do this just like you are doing it in perl: (void)((y = x) || (y = x 1));
CodePudding user response:
well you could always do (x * x) 1 a number squared can never be negative (unless imaginary) and if both equal zero the result would be 1