I'm working on program wich has to repetitively compute:
uint64_t funct()
{
if(x & 1)
{
x=(x * a b) >> 1;
}
else
{
x=(x >> 1) * c d;
}
return x;
}
But it is about 2 times slower than just:
uint64_t funct()
{
x=(x * a b) >> 1;
return x;
}
a,b,c,d,x are some 64-bit numbers and x is randomly odd or even. In general I wouldn't expect this, because the main operation in both cases is multiplication with addition. I don't understand why simple condition slows it down twice.
Can it be done somehow faster?
CodePudding user response:
It slower 2 times because if
is one operation. You can try remove else
part, theorically, result will be the same.
And why you want to compute that fast? Other process such as loop, function call and print to console will cost much more time
CodePudding user response:
Are you compiling with max optimization flags? The compiler in some cases may optimize that condition.
In general I wouldn't expect this, because the main operation in both cases is multiplication with addition. I don't understand why simple condition slows it down twice.
A simple condition requires branching. It should take no time at all, unless if it's hot code. Branching too much in hot code can significantly slow down your program. Check this question and the answers, especially the benchmarking part.
As said in that answer, if you really need to optimize out the branching you will need to use some bit twiddling.