如何使用SIMD比较两个向量并获得单个布尔结果? [英] How to compare two vectors using SIMD and get a single boolean result?
本文介绍了如何使用SIMD比较两个向量并获得单个布尔结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个分别为4个整数的向量,我想使用SIMD命令对其进行比较(例如,根据比较结果生成一个结果向量,其中每个条目为0或1).
I have two vectors of 4 integers each and I'd like to use a SIMD command to compare them (say generate a result vector where each entry is 0 or 1 according to the result of the comparison).
然后,我想将结果向量与4个零的向量进行比较,并且仅当它们相等时才做某事.
Then, I'd like to compare the result vector to a vector of 4 zeros and only if they're equal do something.
您知道我可以使用哪些SIMD命令吗?
Do you know what SIMD commands I can use to do it?
推荐答案
比较两个SIMD向量:
To compare two SIMD vectors:
#include <stdint.h>
#include <xmmintrin.h>
int32_t __attribute__ ((aligned(16))) vector1[4] = { 1, 2, 3, 4 };
int32_t __attribute__ ((aligned(16))) vector2[4] = { 1, 2, 2, 2 };
int32_t __attribute__ ((aligned(16))) result[4];
__m128i v1 = _mm_load_si128((__m128i *)vector1);
__m128i v2 = _mm_load_si128((__m128i *)vector2);
__m128i vcmp = _mm_cmpeq_epi32(v1, v2);
_mm_store_si128((__m128i *)result, vcmp);
注意:
- 假定数据为32位整数
-
vector1
,vector2
,result
都需要对齐16个字节 - 结果等于-1,不等于0(上述代码示例为
{ -1, -1, 0, 0 }
)
- data is assumed to be 32 bit integers
vector1
,vector2
,result
all need to be 16 byte aligned- result will be -1 for equal, 0 for not equal (
{ -1, -1, 0, 0 }
for above code example)
更新
如果在所有4个元素都匹配的情况下,如果只需要一个布尔结果,则可以这样做:
If you just want a single Boolean result for the case where all 4 elements match then you can do it like this:
#include <stdint.h>
#include <xmmintrin.h>
int32_t __attribute__ ((aligned(16))) vector1[4] = { 1, 2, 3, 4 };
int32_t __attribute__ ((aligned(16))) vector2[4] = { 1, 2, 2, 2 };
__m128i v1 = _mm_load_si128((__m128i *)vector1);
__m128i v2 = _mm_load_si128((__m128i *)vector2);
__m128i vcmp = _mm_cmpeq_epi32(v1, v2);
uint16_t mask = _mm_movemask_epi8(vcmp);
int result = (mask == 0xffff);
这篇关于如何使用SIMD比较两个向量并获得单个布尔结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文