Fast sign of integer in C

前端 未结 5 1115
轮回少年
轮回少年 2020-12-06 11:57

There is a sign function in C:

int sign(int x)
{
    if(x > 0) return 1;
    if(x < 0) return -1;
    return 0;
}

Unfortunately, comp

5条回答
  •  余生分开走
    2020-12-06 12:24

    First of all, integer comparison is very cheap. It's branching that can be expensive (due to the risk of branch mispredictions).

    I have benchmarked your function on a Sandy Bridge box using gcc 4.7.2, and it takes about 1.2ns per call.

    The following is about 25% faster, at about 0.9ns per call:

    int sign(int x) {
        return (x > 0) - (x < 0);
    }
    

    The machine code for the above is completely branchless:

    _sign:
        xorl    %eax, %eax
        testl   %edi, %edi
        setg    %al
        shrl    $31, %edi
        subl    %edi, %eax
        ret
    

    Two things are worth pointing out:

    1. The base level of performance is very high.
    2. Eliminating branching does improve performance here, but not dramatically.

提交回复
热议问题