我最近从Matlab切换到了c ++,以便更快地运行仿真,但是运行仍然很慢。我非常肯定在内存使用方面有很多改进。
考虑下面的代码,它显示了我在模拟中使用的两个数组/向量声明的示例。
一个具有已知的固定长度(array01),另一个具有未知的长度(array02)在运行期间会发生变化。
这里的问题是,就内存使用和性能而言,声明变量(对于两种数组类型)的最佳/正确/高效方式是什么?
# include <iostream>
# include <vector>
# include <ctime>
# include <algorithm>
using namespace std;
const int n = 1000;
const int m= 100000;
int main()
{
srand((unsigned)time(NULL));
vector <double> array02;
vector <vector<double>> Array01(n,m);
for (unsigned int i=0; i<n; i++)
{
for (unsigned int j=0; j<m;j++)
{
array02.clear();
rr = rand() % 10;
for (unsigned int l = 0 ; l<rr <l++)
{
array02.pushback(l);
}
// perform some calculation with array01 and array02
}
}
}
最佳答案
您应该考虑使用Matrix
成员函数,void resize(unsigned width, unsigned height)
内联成员函数和/或double get(unsigned i, unsigned j)
内联成员函数(均提供Mi,j元素)定义自己的double& at(unsigned i, unsigned j)
类。矩阵内部数据可以是一维数组或双精度向量。使用向量的向量(所有大小均相同)不是表示矩阵的最佳(或最快)方法。
class Matrix {
std::vector<double> data;
unsigned width, height;
public:
Matrix() : data(), width(0), height(0) {};
~Matrix() = default;
/// etc..., see rule of five
void resize(unsigned w, unsigned h) {
data.resize(w*h);
width = w; height = h;
}
double get(unsigned i, unsigned j) const {
assert(i<width && j<height);
return data[i*width+j];
}
double& at(unsigned i, unsigned j) {
assert(i<width && j<height);
return data[i*width+j];
}
}; // end class Matrix
另请参阅rule of five。
您也可以尝试scilab(它是免费软件)。它类似于Matlab,并且可能具有不同的性能。不要忘记使用最新版本。
顺便说一句,现有大量处理矩阵的C ++数值库。考虑使用其中之一。如果性能至关重要,请在调试之后不要忘记要求编译器优化代码。
假设您使用的是Linux(我建议您使用它进行数值计算;大多数超级计算机都运行Linux,这一点很重要),在调试阶段使用
g++ -std=c++11 -Wall -Wextra -g
进行编译,然后在基准测试期间使用g++ -std=c++11 -Wall -Wextra -mtune=native -O3
。不要忘了profile,并记住过早的优化是有害的(首先需要使程序正确)。您甚至可能花费数周甚至数月甚至数年的时间来使用OpenMP,OpenCL,MPI,pthreads或std::thread之类的技术来实现parallelization(这是一个很难的主题),需要几年的时间来掌握)。
如果矩阵很大,并且/或者具有其他属性(例如sparse,triangular,symmetric等),则需要掌握许多数学和计算机科学知识来提高性能。您可以对此进行博士学位,并将您的一生都花在该主题上。因此,请转到您的大学图书馆阅读有关numerical analysis和linear algebra的一些书籍。
对于随机数,C++11给您
<random>
; BTW使用C ++ 11或C ++ 14,而不是某些较早版本的C ++。另请阅读http://floating-point-gui.de/和一本有关C++ programming的好书。
PS。我对数值计算没有任何特别的专长。我更喜欢符号计算。
关于c++ - 带有内存管理的高效编码,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32859532/