cif-statementvisual-studio-2012simdauto-vectorization

How to avoid if statement? for the compiler cannot optimize it to simd


In vs2012 the compiler can automatically optimize the for loop into SIMD assembly statement. But when a if statment is in the for loop, the compiler cannot optimize it, just like:

for(int i=0; i<10000; i++)
{
    if(a[i]<1)
    {
        a[i]=0;
    }
}

Is there anyway to replace the if statments and let the compiler able to automatically optimize it into simd code?


Solution

  • Well, you could try trickery like:

    for(int i=0; i<10000; i++)
        a[i] = a[i] * (a[i] >= 1);
    

    but you should realise a few things.

    First, it may end up still not being able to use SIMD. That'll depend on the compiler and how clever it may be.

    Secondly, it may end up being slower, especially since you're performing a calculation on, and touching, every element in the array. This won't be too bad for the sample but, if your calculation is more complex, that can cause trouble.

    Thirdly, if that is your real code, SIMD isn't really going to help that much for a simple calculation and minimal loop count (10,000 isn't really that much).