1. 程式人生 > >C程式碼中向量運算的幾個例子

C程式碼中向量運算的幾個例子

  最近遇到了一個C語言中使用向量運算的問題,栽了不少跟頭,這裡就做個總結,免得後面再犯類似錯誤.

  該資料結構的定義如下所示:

typedef int v4si __attribute__ ((vector_size (16)))

  基本的操作:

typedef int v4si __attribute__ ((vector_size (16)));

v4si a, b, c;
long l;

a = b + 1;    /* a = b + {1,1,1,1}; */
a = 2 * b;    /* a = {2,2,2,2} * b; */

a 
= l + a; /* Error, cannot convert long to int. */

  特殊的運算:

typedef int v4si __attribute__ ((vector_size (16)));

v4si a = {1,2,3,4};
v4si b = {3,2,1,4};
v4si c;

c = a >  b;     /* The result would be {0, 0,-1, 0}  */
c = a == b;     /* The result would be {0,-1, 0,-1}  */

  使用內斂函式的運算結果:

typedef int v4si __attribute__ ((vector_size (16)));

v4si a = {1,2,3,4};
v4si b = {5,6,7,8};
v4si mask1 = {0,1,1,3};
v4si mask2 = {0,4,2,5};
v4si res;

res = __builtin_shuffle (a, mask1);       /* res is {1,2,2,4}  */
res = __builtin_shuffle (a, b, mask2);    /* res is {1,5,3,6}  */

  一個例子:

#include <stdio.h>

typedef int v4si __attribute__ ((vector_size (16)));

int main()
{
        v4si a = {1,2,3,4};
        v4si b = {5,6,7,8};
        v4si mask1 = {0,1,1,3};
        v4si mask2 = {0,4,2,5};
        v4si res;
        v4si res1;

        res = __builtin_shuffle (a, mask1);       /* res is {1,2,2,4}  */
        res1 = __builtin_shuffle (a, b, mask2);    /* res is {1,5,3,6}  */


        for(int cnt =0; cnt < 4; cnt++)
        {

                printf("%d \n",res[cnt]);
                printf("%d \n",res1[cnt]);
        }

        return 0;
}
~         

  運算結果:

1 
1 
2 
5 
2 
3 
4 
6

  其實,詳細的針對這個概念的解釋請參考後面參考文件,我只是負責知道這個東西怎麼用了.

  參考文件:

1 https://gcc.gnu.org/onlinedocs/gcc/Vector-Extensions.html

2 https://gcc.gnu.org/onlinedocs/gcc-4.0.0/gcc/Vector-Extensions.html