bit-manipulation - 通过 SIMD 查找数组中元素的索引。一个快速的方法

标签 bit-manipulation bitwise-operators simd

我需要通过 SIMD 找到数组 ARR 中 8 位值元素 N 的索引/位置。这一定是快时尚。

目前的算法是,我将 ARR 的 8 位值加载到一个 SIMD 寄存器中,并将字符代码 N 加载到另一个 SIMD 寄存器中。

然后我会使用否定并使用 popcnt 检查哪个字节是成功的。

有没有更快的方法?

如果需要,操作可能会饱和使用。

最佳答案

您使用哪种指令集/架构?这将在一定程度上影响这个问题的“正确”答案。

在上交所:

#include <immintrin.h>
#include <stdio.h>

int byteIndex(__m128i ARR, __m128i N)
{
  __m128i cmp = _mm_cmpeq_epi8(ARR, N);
  int mask = _mm_movemask_epi8(cmp);
  return _tzcnt_u32(mask);
}

int main()
{
  __m128i ARR = _mm_setr_epi8(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15);

  // test case that will work
  __m128i N = _mm_set1_epi8(3);
  printf("%d\n", byteIndex(ARR, N));   ///< prints '3'

  // test case that will fail
  __m128i F = _mm_set1_epi8(16);
  printf("%d\n", byteIndex(ARR, F));   ///< prints '32'

  return 1;
}

关于bit-manipulation - 通过 SIMD 查找数组中元素的索引。一个快速的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58334014/

相关文章:

c++ - 使用SIMD根据另一个 vector 位值计算值的乘积

arm - 有人可以向我解释ARM按位操作吗?

math - 为什么我们需要在做 2 的补码时加 1

c++ - 按位替换两个数字中的位

c - 为什么访问单个 SIMD 元素这么慢

c - 如何执行_mm256_movemask_epi8 (VPMOVMSKB) 的反函数?

java - 如何在没有 '*' 运算符的情况下执行乘法?

c - 在 C 中,如何以通用方式设置任意大小的 int 的前八位

c# - C#中的位运算。如何将 2 long 转换为 bool 结果?

python - 对如何在 python shell 中对 16 位二进制数执行按位运算感到困惑