【问题标题】:Giving an instance of a class a pointer to a struct给类的实例一个指向结构的指针
【发布时间】:2009-09-11 14:27:08
【问题描述】:

我正在尝试在我的矢量类中获得 SSE 功能(到目前为止我已经重写了 3 次。:\)并且我正在执行以下操作:

#ifndef _POINT_FINAL_H_
#define _POINT_FINAL_H_

#include "math.h"

namespace Vector3D
{

#define SSE_VERSION 3

#if SSE_VERSION >= 2

    #include <emmintrin.h>  // SSE2

    #if SSE_VERSION >= 3

        #include <pmmintrin.h>  // SSE3

    #endif

#else

#include <stdlib.h>

#endif

#if SSE_VERSION >= 2

    typedef union { __m128 vector; float numbers[4]; } VectorData;
    //typedef union { __m128 vector; struct { float x, y, z, w; }; } VectorData;

#else

    typedef struct { float x, y, z, w; } VectorData;

#endif

class Point3D
{

public:

    Point3D();
    Point3D(float a_X, float a_Y, float a_Z);
    Point3D(VectorData* a_Data);
    ~Point3D();

    // a lot of not-so-interesting functions

private:

    VectorData* _NewData();

}; // class Point3D

}; // namespace Vector3D

#endif

有效!欢呼!但它比我之前的尝试慢。嘘。

我已经确定我的瓶颈是我用来获取指向结构的指针的 malloc。

VectorData* Point3D::_NewData() 
{ 

#if SSE_VERSION >= 2

    return ((VectorData*) _aligned_malloc(sizeof(VectorData), 16)); 

#else

    return ((VectorData*) malloc(sizeof(VectorData))); 

#endif

}

在类中使用 SSE 的主要问题之一是它必须在内存中对齐才能工作,这意味着重载 new 和 delete 运算符,导致代码如下:

 BadVector* test1 = new BadVector(1, 2, 3);
 BadVector* test2 = new BadVector(4, 5, 6);
 *test1 *= test2;

你不能再使用默认构造函数,你必须像瘟疫一样避免new。

我的新方法基本上是让数据在类外部,这样类就不必对齐。

我的问题是:有没有更好的方法来获取指向结构的(在内存上对齐)实例的指针,或者我的方法真的很愚蠢并且有更清洁的方法?

【问题讨论】:

    标签: c++ struct malloc new-operator sse2


    【解决方案1】:

    怎么样:

    __declspec( align( 16 ) ) VectorData vd;
    

    ?

    您也可以按如下方式创建自己的 operator new 版本

    void* operator new( size_t size, size_t alignment )
    {
         return __aligned_malloc( size, alignment );
    }
    

    然后可以进行如下分配

    AlignedData* pData = new( 16 ) AlignedData;
    

    在 16 字节边界处对齐。

    如果那没有帮助,那么我可能会误解您的要求......

    【讨论】:

    • 你的意思是_declspec,我猜?
    • LOL 真的没有注意到那个错字!!
    【解决方案2】:

    您可能不应该期望一次性向量的性能得到提高。当您可以将并行处理与一些体积相结合时,即当按顺序处理 许多 个向量时,并行处理会最亮。

    【讨论】:

      【解决方案3】:

      我修好了。 :O

      这真的很容易。我所要做的就是转身

      VectorData* m_Point;
      

      进入

      VectorData m_Point;
      

      我的问题消失了,不需要 malloc 或对齐。

      但我感谢大家的帮助! :D

      【讨论】:

      • 抱歉,我对此表示怀疑。是的,x86-64 上的 MS 编译器在 16 字节边界上对齐(不适用于 32 位平台)。如果没有明确说明,我怀疑 ICC 是否会总是在堆栈上对齐 16 字节,而正是因为它试图生成真正快速的代码。 declspec 将是必要的,resp。相应的 gcc 选项。
      猜你喜欢
      • 1970-01-01
      • 2019-03-18
      • 1970-01-01
      • 1970-01-01
      • 2018-05-16
      • 1970-01-01
      • 2015-05-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多