AVX指令集

使用Linux:

1.查看CPU所支持的指令集

对于Linux系统,可运行cat /proc/cpuinfo | grep flags来查看当前CPU所支持的指令集:

由此可知,我CPU支持AVX2指令集,但是不支持AVX-512指令集。
              

二、Ubuntu中运行问题一:编译错误

#include<immintrin.h>
#include<iostream>
#include<cmath>
#include <cstdio>
using namespace std;

void sinx(int, int, float*, float*);
void print_MM(__m256);

int main()
{
        int N = 8, terms = 3;
        float x[8] = { 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8 }, result[8];
        sinx(N, terms, x, result);
        for (int i = 0; i < N; ++i)
        {
                printf("sin(%.3f) = %.10f;%.10f\n", x[i], result[i], sin(x[i]));
        }
        return 0;
}

void sinx(int N, int terms, float* x, float* result)
{
        float three_fact = 6;
        for (int i = 0; i < N; i += 8)
        {
                __m256 origx = _mm256_loadu_ps(&x[i]);
                print_MM(origx);
                __m256 value = origx;
                __m256 numer = _mm256_mul_ps(origx, _mm256_mul_ps(origx, origx));
                __m256 denom = _mm256_broadcast_ss(&three_fact);


                int sign = -1;

                for (int j = 1; j <= terms; j++)
                {
                        //value += sign * numer / denom
                        __m256 tmp1 = _mm256_div_ps(_mm256_mul_ps(_mm256_set1_ps(sign), numer), denom);
                        value = _mm256_add_ps(value, tmp1);
                        numer = _mm256_mul_ps(numer, _mm256_mul_ps(origx, origx));
                        float tmp2 = (float)((2 * j + 2) * (2 * j + 3));
                        denom = _mm256_mul_ps(denom, _mm256_broadcast_ss(&tmp2));
                        sign *= -1;
                }
                _mm256_storeu_ps(&result[i], value);
        }
}
void print_MM(__m256 test)
{
        float out[8];
        _mm256_storeu_ps(&out[0], test);
        for (int i = 0; i < 8; ++i)
        {
                cout << out[i] << "  ";
        }
        cout << endl;
}

将这份代码(上面代码已经是改正过的代码)复制到Linux系统利用如下命令编译

使用上述编译命令正确编译后,运行无结果

发现原因是因为内存不对齐,所使用的_mm256_load_ps()和_mm256_store_ps()等操作要求内存地址以32对齐。而直接定义来的float数组并非如此,可以直接输出变量地址进行验证

最终也找到两个解决方法

方法一:使用不严格对齐操作
_mm256_loadu_ps() 代替 _mm256_load_ps()
_mm256_storeu_ps() 代替_mm256_store_ps()
等等

方法二:定义变量时规定内存对齐
根据编译器的不同而有不同的具体要求,在本例中我使用GCC编译器,因而具体改动如下

__attribute__ ((aligned (32))) float x[8] = { 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8 }, result[8];
__attribute__ ((aligned (32))) float out[8];

使用了方法一,编译后运行如下:


原文链接:https://blog.csdn.net/zachariah2000/article/details/120731767

原文链接:https://blog.csdn.net/mutourend/article/details/100074798

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值