0

我有一个与此类似的向量结构设置:它是 128 位对齐的,就像 __m128 类型一样。

struct Vector3
{
    union
    {
        float v[4];
        struct { float x,y,z,w; }
    }
}

我正在使用 SSE 4.1 点积指令 _mm_dp_ps。是否需要为我的以上结构使用 _mm_load_ps 已经对齐 128 位,或者我可以直接转换我的结构吗?这是安全的做法吗?

注意:使用 VS2013 并包含。

使用 _mm_load_ps 的当前代码:

float Vector3::Dot(const Vector3 & v) const
{
    __m128 a = _mm_load_ps(&this->v[0]);
    __m128 b = _mm_load_ps(&v.v[0]);

    __m128 res = _mm_dp_ps(a, b, 0x71);
    return res.m128_f32[0];
}

问题代码:

float Vector3::Dot(const Vector3 & v) const
{
    __m128 res = _mm_dp_ps(*(__m128*)&this->v[0], *(__m128*)&v.v[0], 0x71);
    return res.m128_f32[0];
}

编辑:做了一些测试

使用这个简单的控制台应用程序代码,我运行了 3 个不同的测试。第一次使用 _mm_load_ps,第二次将结构转换为 __m128 类型,最后使用联合内部的 __m128 类型。

union Vector4
{
    Vector4(float x, float y, float z, float w) { a = x; b = y; c = z; d = w; }
    struct {float a, b, c, d;};
    __m128 m;
};

int _tmain(int argc, _TCHAR* argv[])
{
    const Vector4 vector_a = Vector4(1.0f, 2.0f, 3.0f, 4.0f);
    const Vector4 vector_b = Vector4(10.0f, 20.0f, 30.0f, 40.0f);

    unsigned long long start;

    // : Test Using _mm_load_ps :
    start = GetTickCount64();
    for (unsigned long long i = 0; i < 10000000000U; i++)
    {
        __m128 mx = _mm_load_ps((float*)&vector_a);
        __m128 my = _mm_load_ps((float*)&vector_b);

        __m128 res_a = _mm_add_ps(mx, my);
    }
    unsigned long long end_a = GetTickCount64() - start;

    // : Test Using Direct Cast to __m128 type :
    start = GetTickCount64();
    for (unsigned long long i = 0; i < 10000000000U; i++)
    {
        __m128 res_b = _mm_add_ps(*(__m128*)&vector_a, *(__m128*)&vector_b);
    }
    unsigned long long end_b = GetTickCount64() - start;

    // : Test Using __m128 type in Union :
    start = GetTickCount64();
    for (unsigned long long i = 0; i < 10000000000U; i++)
    {
        __m128 res_c = _mm_add_ps(vector_a.m, vector_b.m);
    }
    unsigned long long end_c = GetTickCount64() - start;

    return 0;
}

结果是: end_a : 26489 滴答 end_b : 19375 滴答 end_c : 18767 滴答

我也单步执行了代码,从 res_a 到 res_c 的所有结果都是正确的。所以这个测试表明使用联合更快。

我知道默认情况下 __m128 类型是对使用的寄存器的引用,而不是类型,但是当包含 smmintrin.h 时,__m128 成为 xmmintrin.h 中定义为的联合

typedef union __declspec(intrin_type) _CRT_ALIGN(16) __m128 {
     float               m128_f32[4];
     unsigned __int64    m128_u64[2];
     __int8              m128_i8[16];
     __int16             m128_i16[8];
     __int32             m128_i32[4];
     __int64             m128_i64[2];
     unsigned __int8     m128_u8[16];
     unsigned __int16    m128_u16[8];
     unsigned __int32    m128_u32[4];
} __m128;

所以我相信使用内在包含执行的指令不是引用寄存器,而是引用 xmmintrin.h 中定义的 __m128 类型。

因此,为了在此测试后更好地重复我的问题:在结构内部使用 xmmintrin.h 中定义的 __m128 结构与 Visual Studio 2013 可用的内在函数一起使用是否安全?

4

0 回答 0