c++ - AltiVec vec_msum 等效于浮点值

标签 c++ vector floating-point simd altivec

有人知道针对浮点值 vector 实现 vec_msum 功能的方法吗?

我对 SIMD 还很陌生,虽然我认为我已经开始理解它了 - 仍然有一些谜题。

我的最终目标是重写函数“convolve_altivec”(如 this 问题的接受答案中所示),以便它接受浮点值而不是短值的输入参数。

也就是说,原型(prototype)应该是

float convolve_altivec(const float *a, const float *b, int n)

我正在尝试匹配以下原始非优化函数提供的功能:

float convolve(const float *a, const float *b, int n)
{
    float out = 0.f;
    while (n --)
        out += (*(a ++)) * (*(b ++));
    return out;
}

我最初的努力是尝试将同一函数的现有 SSE 版本移植到 altivec 指令。

最佳答案

对于 float 版本,您需要vec_madd

这是我为回答您之前的问题而发布的先前 16 位 int 版本和测试工具的浮点版本:

#include <assert.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <altivec.h>

static float convolve_ref(const float *a, const float *b, int n)
{
    float sum = 0.0f;
    int i;

    for (i = 0; i < n; ++i)
    {
        sum += a[i] * b[i];
    }

    return sum;
}

static inline float convolve_altivec(const float *a, const float *b, int n)
{
    float sum = 0.0f;
    vector float vsum = { 0.0f, 0.0f, 0.0f, 0.0f };
    union {
        vector float v;
        float a[4];
    } usum;

    vector float *pa = (vector float *)a;
    vector float *pb = (vector float *)b;

    assert(((unsigned long)a & 15) == 0);
    assert(((unsigned long)b & 15) == 0);

    while (n >= 4)
    {
        vsum = vec_madd(*pa, *pb, vsum);
        pa++;
        pb++;
        n -= 4;
    }

    usum.v = vsum;

    sum = usum.a[0] + usum.a[1] + usum.a[2] + usum.a[3];

    a = (float *)pa;
    b = (float *)pb;

    while (n --)
    {
        sum += (*a++ * *b++);
    }

    return sum;
}

int main(void)
{
    const int n = 1002;

    vector float _a[n / 4 + 1];
    vector float _b[n / 4 + 1];

    float *a = (float *)_a;
    float *b = (float *)_b;

    float sum_ref, sum_test;

    int i;

    for (i = 0; i < n; ++i)
    {
        a[i] = (float)rand();
        b[i] = (float)rand();
    }

    sum_ref = convolve_ref(a, b, n);
    sum_test = convolve_altivec(a, b, n);

    printf("sum_ref = %g\n", sum_ref);
    printf("sum_test = %g\n", sum_test);

    printf("%s\n", fabsf((sum_ref - sum_test) / sum_ref) < 1.0e-6 ? "PASS" : "FAIL");

    return 0;
}

关于c++ - AltiVec vec_msum 等效于浮点值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4384414/

相关文章:

floating-point - 为什么我们偏向 float 的指数?

java - 将wav音频格式字节数组转换为 float

c++ - 学校作业的简单密码加密

c++ - 打印指向成员字段的指针

c++ - 两个不等大小的 vector 是否存在 std::mismatch?

由结构 vector 引起的 C++ 内存泄漏

c++ - 为什么 unique_ptr 不阻止自定义删除器的切片?

c++ - 使用模板元编程来包装 C 风格的可变参数

C++ std::copy 输入迭代器(指针)到 vector

ios - NSString float ……如果NSString不是数字并且包含字母数字字符,会发生什么?