AVX2浮点向量运算

在C/C++程序中,使用AVX2指令有很多种方法。

嵌入汇编是一般的方法,但是对于不熟悉汇编语言的人来说,有点勉为其难。

gcc编译支持AVX2指令的编程。程序中需要使用头文件<immintrin.h>和<avx2intrin.h>,这样通过调用其中定义的一些函数,达到使用AVX2指令目的,即用C/C++调用SIMD指令(单指令多数据)

这里给出的样例程序是有关浮点向量运算的例子。

其中函数_mm_add_ps()实现的是浮点向量(4个数)加法运算。样例程序中使用了若干有关avx2的函数。

编程操作系统是Ubuntu15.10,使用Qt编写程序,编译器是gcc的版本是5.2.1

使用AVX2指令实现向量运算,由于使用的是SIMD指令,其优点在于各个分量是并行计算的,计算速度相对比较快。

浮点向量运算样例程序1:

/* 浮点向量运算 */

#include <iostream>
#include <immintrin.h>
#include <avx2intrin.h>

using namespace std;

int main()
{
    __m128  a;
    __m128  b;
    __m128  c;

    float op1[4] = {1.1, 2.2, 3.3, 4.4};
    float op2[4] = {2.2, 3.3, 4.4, 5.5};
    float result[4];

    // Load
    a = _mm_load_ps(op1);
    b = _mm_load_ps(op2);

    // Calculate
    c = _mm_add_ps(a, b);   // c = a + b

    // Store
    _mm_store_ps(result, c);

    printf("0: %lf
", result[0]);
    printf("1: %lf
", result[1]);
    printf("2: %lf
", result[2]);
    printf("3: %lf
", result[3]);

    return 0;
}

运算结果:

0: 8.000000
1: 6.000000
2: 4.000000
3: 2.000000

浮点向量运算样例程序2:

/* 浮点向量运算 */

#include <iostream>
#include <immintrin.h>
#include <avx2intrin.h>

using namespace std;

int main()
{
    __m128  a;
    __m128  b;
    __m128  c;

    float op1[4] = {1.1, 2.2, 3.3, 4.4};
    float op2[4] = {2.2, 3.3, 4.4, 5.5};
    float result[4];

    // Load
    a = _mm_load_ps(op1);
    b = _mm_load_ps(op2);

    // Calculate
    c = _mm_add_ps(a, b);   // c = a + b

    // Store
    _mm_store_ps(result, c);

    printf("0: %lf
", result[0]);
    printf("1: %lf
", result[1]);
    printf("2: %lf
", result[2]);
    printf("3: %lf
", result[3]);

    return 0;
}

运算结果:

0: 3.300000
1: 5.500000
2: 7.700000
3: 9.900000


原文地址:https://www.cnblogs.com/tigerisland/p/7564244.html