c++ stack efficient for multicore application
c++ stack efficient for multicore application
我正在尝试用 C++ 编写多代码马尔可夫链,同时我正在尝试利用许多 CPU(最多 24 个)到 运行 个不同的链,我在选择合适的容器来收集每个 CPU 的数值评估结果时遇到问题。我要测量的基本上是布尔变量数组的平均值。我已经尝试围绕一个看起来像这样的 `std::vector`` 对象编写一个包装器:
struct densityStack {
vector<int> density; //will store the sum of boolean varaibles
int card; //will store the amount of elements we summed over for normalizing at the end
densityStack(int size){ //constructor taking as only parameter the size of the array, usually size = 30
density = vector<int> (size, 0);
card = 0;
}
void push_back(vector<int> & toBeAdded){ //method summing a new array (of measurements) to our stack
for(auto valStack = density.begin(), newVal = toBeAdded.begin(); valStack != density.end(); ++valStack, ++ newVal)
*valStack += *newVal;
card++;
}
void savef(const char * fname){ //method outputting into a file
ofstream out(fname);
out.precision(10);
out << card << "\n"; //saving the cardinal in first line
for(auto val = density.begin(); val != density.end(); ++val)
out << << (double) *val/card << "\n";
out.close();
}
};
然后,在我的代码中,我使用单个 densityStack
对象,每次 CPU 核心有数据(每秒可以 100 次)它会调用 push_back
发送数据返回 densityStack
.
我的问题是,这似乎比第一种原始方法慢,在第一种方法中,每个核心将每个测量数组存储在文件中,然后我使用一些 Python 脚本来平均和清理(我对这是因为存储了太多信息并在硬盘驱动器上引起了太多无用的压力。
您看到我在哪些地方会损失很多性能吗?我的意思是有明显的开销来源吗?因为对我来说,即使在 1000Hz 的频率下复制回矢量也不应该太多。
您如何同步共享的 densityStack 实例?
从这里有限的信息来看,我的猜测是 CPU 每次有一小块数据时都被阻塞等待写入数据。如果这是问题所在,提高性能的一种简单技术是减少写入次数。为每个 CPU 保留一个数据缓冲区,并减少写入 densityStack 的频率。
我正在尝试用 C++ 编写多代码马尔可夫链,同时我正在尝试利用许多 CPU(最多 24 个)到 运行 个不同的链,我在选择合适的容器来收集每个 CPU 的数值评估结果时遇到问题。我要测量的基本上是布尔变量数组的平均值。我已经尝试围绕一个看起来像这样的 `std::vector`` 对象编写一个包装器:
struct densityStack {
vector<int> density; //will store the sum of boolean varaibles
int card; //will store the amount of elements we summed over for normalizing at the end
densityStack(int size){ //constructor taking as only parameter the size of the array, usually size = 30
density = vector<int> (size, 0);
card = 0;
}
void push_back(vector<int> & toBeAdded){ //method summing a new array (of measurements) to our stack
for(auto valStack = density.begin(), newVal = toBeAdded.begin(); valStack != density.end(); ++valStack, ++ newVal)
*valStack += *newVal;
card++;
}
void savef(const char * fname){ //method outputting into a file
ofstream out(fname);
out.precision(10);
out << card << "\n"; //saving the cardinal in first line
for(auto val = density.begin(); val != density.end(); ++val)
out << << (double) *val/card << "\n";
out.close();
}
};
然后,在我的代码中,我使用单个 densityStack
对象,每次 CPU 核心有数据(每秒可以 100 次)它会调用 push_back
发送数据返回 densityStack
.
我的问题是,这似乎比第一种原始方法慢,在第一种方法中,每个核心将每个测量数组存储在文件中,然后我使用一些 Python 脚本来平均和清理(我对这是因为存储了太多信息并在硬盘驱动器上引起了太多无用的压力。
您看到我在哪些地方会损失很多性能吗?我的意思是有明显的开销来源吗?因为对我来说,即使在 1000Hz 的频率下复制回矢量也不应该太多。
您如何同步共享的 densityStack 实例?
从这里有限的信息来看,我的猜测是 CPU 每次有一小块数据时都被阻塞等待写入数据。如果这是问题所在,提高性能的一种简单技术是减少写入次数。为每个 CPU 保留一个数据缓冲区,并减少写入 densityStack 的频率。