c++ - 优化 C++ 二维数组

标签 c++ linux optimization gcc stl

我需要一种方法来表示 C++ 中 double 的二维数组(密集矩阵),并且访问开销绝对最小。

我在各种 linux/unix 机器和 gcc 版本上做了一些计时。 vector 的 STL vector ,声明为:

vector<vector<double> > matrix(n,vector<double>(n));

通过 matrix[i][j] 访问的访问速度比声明如下的数组慢 5% 到 100%:

double *matrix = new double[n*n];

通过内联索引函数matrix[index(i,j)]访问,其中index(i,j)计算为i+n*j。在没有 STL 的情况下排列二维数组的其他方法 - 一个包含 n 个指针的数组,指向每行的开头,或者将堆栈上的整个事物定义为恒定大小 matrix[n][n] - 以与索引函数方法几乎完全相同的速度运行。

最近的 GCC 版本 (> 4.0) 似乎能够编译 STL vector 的 vector ,当打开优化时,其效率几乎与非 STL 代码相同,但这在某种程度上取决于机器。

如果可能,我想使用 STL,但必须选择最快的解决方案。有没有人有使用 GCC 优化 STL 的经验?

最佳答案

如果您使用的是 GCC,编译器可以分析您的矩阵访问并在某些情况下更改内存中的顺序。魔术编译器标志定义为:

-fipa-matrix-reorg

Perform matrix flattening and transposing. Matrix flattening tries to replace a m-dimensional matrix with its equivalent n-dimensional matrix, where n < m. This reduces the level of indirection needed for accessing the elements of the matrix. The second optimization is matrix transposing that attemps to change the order of the matrix's dimensions in order to improve cache locality. Both optimizations need fwhole-program flag. Transposing is enabled only if profiling information is avaliable.

请注意,此选项未通过 -O2 或 -O3 启用。你必须自己通过它。

关于c++ - 优化 C++ 二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/152745/

相关文章:

c - 一次又一次分配相同的内存空间

java - Linux 上 Maven exec/debug 插件下的 Unsatisfied link 错误

optimization - 8051汇编语言有哪些内存优化技术?

C++ 编译器错误 "no matching function"

c++ - MSVC++ 中的源字符集编码规范,如 gcc "-finput-charset=CharSet"

c++ - "class"在构造函数中意味着什么?

c++ - 我什么时候应该使用 std::any

c - read() 系统调用实际读取的数据量

c++ - 将 void 函数作为参数传递给 c++ 中的 double 函数

python-3.x - 质数和最小值 - 超出 python 时间限制