【问题标题】:How to access and manage block stored data如何访问和管理块存储数据
【发布时间】:2012-11-04 15:16:30
【问题描述】:

我想做的事:我需要以块的形式存储单元格数据,即

*cell_member1[cell0] .. cell_member1[cellN] ... cell_memberM[cell0] .. cell_memberM[cellN]*

然后我需要有效地访问这些数据,如果可能的话,使用一个好的语法。如果我可以轻松定义要存储的数据,那就太好了,即通过将具有成员的对象定义为我想要存储的数据并将其传递给为我做所有事情的“魔法”。

动机:为什么我需要这样做?缓存垃圾。在某些内部循环中,仅访问对象的某些成员。用未使用的内存浪费一半的缓存行不是我的应用程序的选择。我可以将指针存储在指向某个顺序内存区域的对象中。这会浪费内存并迫使我在该区域使用不同的语法。

我目前是怎么做的:我有一个容器的形式:

template<class T> struct Container {
  char* data;
  Container(const int n) {
    data = new char[n*T::spaceRequirements()]; //< Data stored "block-wise"
    new(data) typename T::Flags[n]; //< Flags stored "cell-wise"
  }
  /// Destructor ommited for briefness.
};

我在其中存储 T 类型的某些单元格的数据。每个单元格需要一些标志,现在我正在使用 std::bitset 来存储它们,这意味着我需要以单元格形式存储这些位集:

*cell_member1[cell0] ... cell_memberM[cell0] ... cell_member1[cellN] .. cell_memberM[cellN]*

我正在描述每个单元格需要存储多少数据在以下类中,该类还提供对数据的访问:

template<int nd> struct CellAccessor {
  /// Cell flags are stored cell-wise:
  typedef std::bitset<64> Flags;
  enum { DELETE = 0, ///< Cell marked for deletion
         REFINE = 1 ///< Cell marked for refinement
         //...
  }; ///< Enum for the flags.
  static inline Flags& flags(const int cellId) {
    return *reinterpret_cast<Flags*>(data + sizeof(Flags)*cellId); }
  template<int pId> static inline Flags::reference flags(const int cellId) {
    return flags(cellId)[pId]; } //< Cell-wise access to the properties

  /// The rest of the data is stored block-wise:
  static inline int& order(const int cellId) { ///< One int field.
    return *reinterpret_cast<int*>
        (data + maxNoCells*sizeof(Flags) + sizeof(int)*cellId);}

  /// Coordinate vector with nd components:
  static inline double& coordinates(const int cellId, const int i) {
    return *reinterpret_cast<double*>
        (data + maxNoCells*(sizeof(Flags)+sizeof(int))
         + maxNoCells*i*sizeof(double) + sizeof(double)*cellId); }
  template<int i> static inline double& coordinates(const int cellId) {
    return *reinterpret_cast<double*>
        (data +maxNoCells*(sizeof(Flags)+sizeof(int)+i*sizeof(double))
         + sizeof(double)*cellId); }

  /// Total amount of memory to allocate per cell: (used by Container)
  static inline int spaceRequirements() { return
        sizeof(Flags) // Flags
        + sizeof(int) // order
        + nd*sizeof(double) // coordinates
        ;}

  /// Constructor gets pointer to the beginning of the container 
  /// and the offset for the member variables:
  CellAccessor(char* d, int n){data = d; maxNoCells = n;}
 private:
  static char* data;  ///< Pointer to the beginning of the container.
  static int maxNoCells;  ///< Cell offset for the member variables.
};
template<int nd> char* CellAccessor<nd>::data = nullptr;
template<int nd> int CellAccessor<nd>::maxNoCells = 0;

我是这样使用它的:

int main() {
  int maxNoCells = 10000;   ///< Maximum number of cells (=cell offset).
  typedef CellAccessor<2> A;
  Container< A > cellData(maxNoCells);  ///< Allocate cell data.
  A cells(cellData.data,maxNoCells);  ///< Provides access to cell data.

  for(int i = 0; i < maxNoCells; ++i){
    cells.flags<A::DELETE>(i) = i%2==0 ? true : false;
    cells.flags<A::REFINE>(i) = i%2==0 ? false : true;
    cells.coordinates(i,0) = i;
    cells.coordinates<1>(i) = -((double)i);
    cells.order(i) = 2;
  }
}

优点:

  • 数据是块状的,这正是我所需要的。

  • 语法没问题。

问题:

  • 我的课程做得太多:为用户提供对数据的访问,为容器提供需要存储多少数据,为我的数据结构提供数据应该如何移动/复制/交换(哪些是树...)...

  • 我不能使用没有迭代器的 STL 算法。我通过让迭代器存储单元索引并在其中重新实现 CellAccessor 类来实现迭代器(糟糕!干!)。

  • Bitset 仍以单元格形式存储。我可以为我的块级数据结构重新实现 bitset...

  • data 和 maxNoCells 是静态变量,但如果需要,我可以将它们设为普通成员变量。

问题:是否有任何有效的方法来以块形式存储“对象”(或我们在概念上理解的对象)并像存储在 std 容器中一样访问它们,例如向量?

【问题讨论】:

  • 先看看std::aligned_storage
  • @AndrewTomazos-Fathomling 谢谢,看起来很有趣。
  • 对于像我这样不明白的人,为什么 std::vector 不适合这份工作?
  • @Jem 因为缓存垃圾。在 std::vector 中,POD 的成员在内存中连续对齐。这意味着当您访问一个成员时,8 个内存字将被复制到从该成员开始的高速缓存行,即使您只使用这些字中的前 2 个字。这意味着内存带宽减少了 4 倍。现代 CPU 受内存限制。

标签: c++ performance design-patterns data-structures iterator


【解决方案1】:

您想要的是一种“基于列”的内存访问样式

您可以使用std::vector 作为列类型轻松实现它,或者使用自己的底层内存管理创建自己的“列”类型 - 但std::vector 应该可以正常工作

现在,一旦您有了列类型,就可以创建“TABLE”类型。

在某种程度上,您的表格只是一个向量的向量。您当然可以将其包装起来以获得更好看的访问器(如果您想先按行(对象)访问,然后按列(属性)访问。

这是我认为最好的通用方法。

即使在您的特定情况下 - 由于您想使用位长标志来节省内存,正如 Bart van Ingen Schenau 所提到的,您可以使用vector&lt;bool&gt; 所以一般方法是有效的

【讨论】:

  • 谢谢!这么低的水平我看不到森林。我只是使用 std::vectors 重写了整个内容。它看起来很干净。将来我将实现一个自定义分配器,并且应该这样做(我已经说过很多次了,但从未接近它:D :'()。
  • @gnzlbg 很高兴为您提供帮助。为什么不将问题标记为已回答呢? :-) 我了解分配器,不知道有谁真正喜欢实现它们...
【解决方案2】:

我会使用并行数组来满足要求:

template <int nd>
class CellAccessor {
public:
    enum { DELETE = 0, ///< Cell marked for deletion
           REFINE = 1, ///< Cell marked for refinement
           //...
           NUM_FLAGS
    }; ///< Enum for the flags.
    CellAccessor(int numCells) {
        for (int i=0; i<NUM_FLAGS; i++) { m_flags[i] = new bool[numCells]; }
        m_order = new int[numCells];
        for (int i=0; i<nd; i++) { m_coordinates[i] = new double[numCells]; }
    }
    // Destructor, copy-constructor & assignment operator omitted for brevity

    template<int F> inline bool& flags(const int cellId) {
        return m_flags[F][cellId]; }
    inline bool& flags(const int cellId, int flag) {
        return m_flags[flag][cellId]; }
    inline int& order(const int cellId) {
        return m_order[cellId]; }
    template<int i> inline double& coordinates(const int cellId) {
        return m_coordinates[i][cellId]; }
    inline double& coordinates(const int cellId, int i) {
        return m_coordinates[i][cellId]; }

private:
    bool* m_flags[NUM_FLAGS];
    int*  m_order;
    double* m_coordinates[nd];
};

【讨论】:

  • 嗨!感谢您的回答!但是,标志的内存需求刚刚从 1 位增加到 4 字节。
  • 此外,为每个数组调用 new 不是一种选择,因为它可能会导致 std::bad_alloc 错误。我解释说:假设您有 64Gb 的内存,并且每个阵列都有几个 Gb 长。如果您为每个数组分配一个连续的内存块,并且 new 不会将它们连续放置,那么内存布局中的“漏洞”将阻止您接近那些 64Gb 的内存。您需要先分配一大块内存并传递一个指向您希望他们执行分配的位置的指针来帮助 new/malloc。
  • @gnzlbg:您可以通过将bool* 替换为std::vector&lt;bool&gt; 来降低存储要求,该std::vector&lt;bool&gt; 已优化为每个元素仅使用一个位。剩下的,这就是你想要一个 C++ 不直接支持的内存布局所必须付出的代价。
  • 很遗憾我必须付钱。我希望在给定类定义的情况下,有一些通用库可以为我提供这样的抽象,但似乎并非如此。
【解决方案3】:

不确定是否正确理解了这个问题。看起来您正在尝试在顺序字节数组中分配数据。为什么? 但无论如何你都可以通过使用数组来做到这一点:

class Cell {
   std::bitset<64> flags;
   int order;
   double coordinates[2];
}

int main() {
   const int maxNoCells = 10000;
   Cell cells[maxNoCells];

   for(int i = 0; i < maxNoCells; i++) {
       cells[i].flags = ...;
       cells[i].coordinates[0] = i;
       cells[i].coordinates[1] = -i;
       cells[i].order=2;
   }
}

然后根据需要将其转换为 (char *) 单元格。您的类将在连续的内存条中以分段方式分配。您可以将其用于读/写/网络。唯一的问题是您必须特别注意 32/64 位对齐,如果它是 在不同架构之间共享。

如果您坚持在单独的循环中使用不同的字段,这里有另一个版本,它对于缓存会更好一些:

template<int size>
class CellAccessor {
    std::bitset<64> flags[size];
    int order[size];
    double coordinates[size][2];
 public:
    std::bitset<64> &getFlags(int id) {
        return flags[id];
    }
    int &getOrder(int id) {
        return order[id];
    }
    ...
 }


main() {

    CellAccessor<10000> ca;

    for(...i++) {
        ca.getOrder(i) = 2;
        ca.getCoordinates(i)[0] = i;
        ...
    }
 }

【讨论】:

  • 感谢您的回答!我为这个问题添加了一个“动机”。
  • 我刚刚修改了我的代码以更好地反映您的建议。即使用于缓存优化,它仍然可以达到目的。有了这个定义,它就非常紧凑,并且没有填充任何内存。如果您试图节省填充蚂蚁,您的方法可能会更有趣,您的架构允许对数据进行非对齐访问。但一般来说,如果出现问题,请转移字段以减小结构的整体大小。
  • 还有一个提示,即使您同意您的建议,您也可以在 CellAccessor 类中重载 'operator [] (int)',这样语法看起来会更好。
  • 您是对的,在您的代码中,数据非常紧凑,不会浪费任何内存。问题是当您在代码中访问 order 时,缓存行将部分填充来自坐标的数据。这意味着在我只使用顺序而不是坐标的循环中,我正在浪费内存带宽(与内存不同!)。
  • 然后将字段放在单独的数组中。
猜你喜欢
  • 1970-01-01
  • 2017-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-16
  • 1970-01-01
相关资源
最近更新 更多