Testing equality between two __m128i variables

前端 未结 3 1068
悲&欢浪女
悲&欢浪女 2020-12-09 20:01

If I want to do a bitwise equality test between two __m128i variables, am I required to use an SSE instruction or can I use ==? If not, which SSE i

相关标签:
3条回答
  • 2020-12-09 20:12

    Although using _mm_movemask_epi8 is one solution, if you have a processor with SSE4.1 I think a better solution is to use an instruction which sets the zero or carry flag in the FLAGS register. This saves a test or cmp instruction.

    To do this you could do this:

    if(_mm_test_all_ones(_mm_cmpeq_epi8(v1,v2))) {
        //v0 == v1
    }
    

    Edit: as Paul R pointed out _mm_test_all_ones generates two instructions: pcmpeqd and ptest. With _mm_cmpeq_epi8 that's three instructions total. Here's a better solution which only uses two instructions in total:

    __m128i neq = _mm_xor_si128(v1,v2);
    if(_mm_test_all_zeros(neq,neq)) {
        //v0 == v1
    }
    

    This generates

    pxor    %xmm1, %xmm0
    ptest   %xmm0, %xmm0
    
    0 讨论(0)
  • 2020-12-09 20:16

    Consider using an SSE4.1 instruction ptest:

    if(_mm_testc_si128(v0, v1)) {if equal}
    
    else {if not} 
    

    ptest computes the bitwise AND of 128 bits (representing integer data) in a and mask, and return 1 if the result is zero, otherwise return 0.

    0 讨论(0)
  • 2020-12-09 20:28

    You can use a compare and then extract a mask from the comparison result:

    __m128i vcmp = _mm_cmpeq_epi8(v0, v1);       // PCMPEQB
    uint16_t vmask = _mm_movemask_epi8(vcmp);    // PMOVMSKB
    if (vmask == 0xffff)
    {
        // v0 == v1
    }
    

    This works with SSE2 and later.

    As noted by @Zboson, if you have SSE 4.1 then you can do it like this, which may be slightly more efficient, as it's two SSE instructions and then a test on a flag (ZF):

    __m128i vcmp = _mm_xor_si128(v0, v1);        // PXOR
    if (_mm_testz_si128(vcmp, vcmp))             // PTEST (requires SSE 4.1)
    {
        // v0 == v1
    }
    

    FWIW I just benchmarked both of these implementations on a Haswell Core i7 using clang to compile the test harness and the timing results were very similar - the SSE4 implementation appears to be very slightly faster but it's hard to measure the difference.

    0 讨论(0)
提交回复
热议问题