how to break from a loop when using sse intrinsics

2019-07-04 23:08发布

问题:

__m128* pSrc1 = (__m128*) string;
__m128 m0 = _mm_set_ps1(0);    //null character

while(1)
{
    __m128 result = __m128 _mm_cmpeq_ss(*pSrc1, m0);

    //if character is \0 then break

    //do some stuff here

    pSrc1++;
}

I have a string whose length can be a multiple of 16. How do I break out of the loop if _mm_cmpeq_ss returns equal?

回答1:

If you're trying to break out of the loop when you first encounter a \0 then you'll need to do something like this:

__m128i* pSrc1 = (__m128i *)string;         // init pointer to start of string
__m128i m0 = _mm_set1_epi8(0);              // vector of 16 `\0` characters

while (1)
{
    __m128i v0 = _mm_loadu_si128(pSrc1);    // get 16 chars from string
    __m128i v1 = _mm_cmpeq_epi8(v0, m0);    // compare all 16 chars with '\0'
    int vmask = _mm_movemask_epi8(v1);      // get 16 comparison result bits
    if (vmask != 0)                         // if any bit is 1
        break;                              // we found a `\0`, break out of loop
    pSrc1++;                                // next 16 characters...
}

If you only want to test for \0 characters in certain positions and ignore any others then you can change the if (vmask != 0) test to something which matches your specific requirements.



标签: c x86 sse simd