与SSE进行交织洗牌的原理

时间:2019-01-04 06:28:37

标签: c++ sse shuffle simd avx

目标:

对于输入的有序列表:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

实现交错式随机播放:

1 9 17 2 10 18 3 11 19 4 12 20 5 13 21 6 14 22 7 15 23 8 16 24

图: enter image description here 过程:

可以通过SSE2中的_mm_shuffle_ps实现以上目标。以下是代码:

#define MAKE_MASK(f3,f2,f1,f0) ((f3<<6)|(f2<<4)|(f1<<2)|f0)
    float fArray[24] = {.0};
    for(size_t i =0;i<24;i++)
        fArray[i] = (i+1);
    __m128 a0 = _mm_loadu_ps(fArray);
    __m128 a1 = _mm_loadu_ps(fArray+4);
    __m128 a2 = _mm_loadu_ps(fArray+8);
    __m128 a3 = _mm_loadu_ps(fArray+12);
    __m128 a4 = _mm_loadu_ps(fArray+16);
    __m128 a5 = _mm_loadu_ps(fArray+20);

    __m128 b0 = _mm_shuffle_ps(a0,a1,MAKE_MASK(2,0,2,0));
    __m128 b3 = _mm_shuffle_ps(a0,a1,MAKE_MASK(3,1,3,1));
    __m128 b1 = _mm_shuffle_ps(a2,a3,MAKE_MASK(2,0,2,0));
    __m128 b4 = _mm_shuffle_ps(a2,a3,MAKE_MASK(3,1,3,1));
    __m128 b2 = _mm_shuffle_ps(a4,a5,MAKE_MASK(2,0,2,0));
    __m128 b5 = _mm_shuffle_ps(a4,a5,MAKE_MASK(3,1,3,1));

    __m128 c0 = _mm_shuffle_ps(b0,b1,MAKE_MASK(2,0,2,0));
    __m128 c3 = _mm_shuffle_ps(b0,b1,MAKE_MASK(3,1,3,1));
    __m128 c1 = _mm_shuffle_ps(b2,b3,MAKE_MASK(2,0,2,0));
    __m128 c4 = _mm_shuffle_ps(b2,b3,MAKE_MASK(3,1,3,1));
    __m128 c2 = _mm_shuffle_ps(b4,b5,MAKE_MASK(2,0,2,0));
    __m128 c5 = _mm_shuffle_ps(b4,b5,MAKE_MASK(3,1,3,1));

    __m128 d0 = _mm_shuffle_ps(c0,c1,MAKE_MASK(2,0,2,0));
    __m128 d3 = _mm_shuffle_ps(c0,c1,MAKE_MASK(3,1,3,1));
    __m128 d1 = _mm_shuffle_ps(c2,c3,MAKE_MASK(2,0,2,0));
    __m128 d4 = _mm_shuffle_ps(c2,c3,MAKE_MASK(3,1,3,1));
    __m128 d2 = _mm_shuffle_ps(c4,c5,MAKE_MASK(2,0,2,0));
    __m128 d5 = _mm_shuffle_ps(c4,c5,MAKE_MASK(3,1,3,1));

     _mm_storeu_ps(fArray,d0);
     _mm_storeu_ps(fArray+4,d1);
     _mm_storeu_ps(fArray+8,d2);
     _mm_storeu_ps(fArray+12,d3);
     _mm_storeu_ps(fArray+16,d4);
     _mm_storeu_ps(fArray+20,d5);

问题

总而言之,将24 float包到6 __m128中,然后将它们改组3次即可达到我的目标。我发现将16个float压缩为4个__m128,然后改组两次可以得到类似的结果。因此,是否存在对大小为4nn=1,2,3,4,...)的float数组进行混洗的一般原则。

此外,任何人都可以帮助澄清以上算法或向我提供相关材料吗?

0 个答案:

没有答案