zoukankan      html  css  js  c++  java
  • 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


  • 相关阅读:
    多叉树
    PowerDesigner设置集锦(2)
    Delphi应用程序在命令行下带参数执行返回命令行提示的问题
    不允许在 '*******' 上使用扩展属性,或对象不存在
    仓库管理系统开发完成
    动态创建Frame窗体(根据类名,除T以外的字母)
    Access中的常用TSQL
    批量删除同类文件(带通配符)
    判断Access数据库中的表或查询是否存在的SQL
    序列化FastReport,重要提示少走弯路
  • 原文地址:https://www.cnblogs.com/tigerisland/p/7564244.html
Copyright © 2011-2022 走看看