Search code examples
coptimizationnanlogarithmbranch-prediction

Branch-free implementation of f(x) := if x == 0 then 0 else (x * log(x))


I have this C function:

double f(int x)
{
    if (x <= 0)
        return 0.0;
    else
        return x * log(x);
}

which I am calling in a tight loop, and would like to get rid of the branch to see if it improves performance.

I cannot use this:

double f(int x)
{
    return x * log(x);
}

because it returns NaN when x == 0 (which is true about 25% of the time.)

Is there another way to implement it so that it returns 0 when x == 0, but still get rid of the branch?

(I am less concerned about negative inputs, because these are errors, whereas zeros are not.)


Solution

  • Any branch free code must contain a calculation of x * log(x) to cover the "normal" case.

    So, before trying to come up with that branch-free code, measure the speed of x * log(x) alone. Unless it's significantly faster than the code you have, there's nothing significant to be gained here. And I suspect it won't be.