Testing equality between two __m128i variables

↘锁芯ラ 提交于 2019-12-18 13:13:04

问题


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 instruction should I use?


回答1:


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



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/26880863/testing-equality-between-two-m128i-variables

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!