c++ - 上交所加成产生垃圾

标签 c++ gcc

我正在尝试比较 SSE float[4] 添加与标准 float[4] 添加。我试过这个:

#include <iostream>
#include <vector>

struct Point4
{
  Point4()
  {
    data[0] = 0;
    data[1] = 0;
    data[2] = 0;
    data[3] = 0;
  }

  float data[4];
};

static float SumOfDifferences(const Point4& a, const Point4& b)
{
  // This function only returns the sum of the sum of the components
  float sumValues = 0.0f;
  for(unsigned int i = 0; i < 4; ++i)
  {
    sumValues += a.data[i] + b.data[i];
  }
  return sumValues;
}

void Standard()
{
  Point4 a;
  a.data[0] = 1;
  a.data[1] = 2;
  a.data[2] = 3;
  a.data[3] = 4;

  Point4 b;
  b.data[0] = 1;
  b.data[1] = 6;
  b.data[2] = 3;
  b.data[3] = 5;

  float total = 0.0f;
  for(unsigned int i = 0; i < 1e6; ++i)
  {
    total += SumOfDifferences(a, b);
  }

  std::cout << "total: " << total << std::endl;
}

void Vectorized()
{
  typedef int v4sf __attribute__ (( vector_size(4*sizeof(float)) ));

  v4sf a;
  float* aPointer = (float*)&a;
  aPointer[0] = 1; aPointer[1] = 2; aPointer[2] = 3; aPointer[3] = 4;

  v4sf b;
  float* bPointer = (float*)&b;
  bPointer[0] = 1; bPointer[1] = 2; bPointer[2] = 3; bPointer[3] = 4;

  float total = 0.0f;
  v4sf result;
  float* resultPointer = (float*)&result;

  for(unsigned int i = 0; i < 1e6; ++i)
  {
    result = a + b; // Vectorized operation

    // Sum the components of the result (this is done with the "total += " in the Standard() loop
    for(unsigned int component = 0; component < 4; ++component)
    {
      total += resultPointer[component];
    }
  }

  std::cout << "total: " << total << std::endl;
}

int main()
{

//  Standard();

  Vectorized();

  return 0;
}

但 Vectorized() 函数的输出为“inf”。当我逐步使用调试器时,“结果”的值似乎是垃圾(我希望它们是 (0, 4, 0, 1) )。我哪里出错了?

最佳答案

尝试 typedef float v4sf __attribute__ (( vector_size(4*sizeof(float)) ));
结果是 2e+07。

关于c++ - 上交所加成产生垃圾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12183806/

相关文章:

c++ - 具有默认值的单参数构造函数是否与默认构造函数相同?

c++ - 为什么有人会用 float 乘法而不是除法

c++ - 在多核 (linux) 中运行进程的命令行参数是什么

gcc - 链接时 '-lfoo'和 '/path/to/libfoo.so'的区别

c - Visual Studio C 编译器是否具有与 GCC 的 -M 等效的功能?

c - GCC 因 fatal error 终止操作

c++ - 为什么我可以在不重载 "="运算符的情况下将一个对象分配给另一个对象?

c++ - 强制 Eigen 在运行时检查矩阵维度

c++ - 如何构建独立于编译器的 C++ 库(适用于 Solaris Studio 和 gcc)?

c - 使用 GCC C 在 AIX 上处理空指针