优化 Eigen 中的大型矩阵乘法

Optimize large matrices multiplication in Eigen

我正在使用 Eigen 库在 C++ 中进行一些大型随机矩阵(至少 1000x1000)计算,我的代码包含以下函数:

Eigen::VectorXd grid(...); initializes (element by element) a sorted vector of log-normally distributed values, using the quicksort algorithm and the ran1 algorithm, let's say of size N, all matrices are then of size NxN.

Eigen::VectorXd conditionGrid(...); a loop that returns a vector containing the grid vector minus a time dependent value.

Eigen::MatrixXd xjkMatrix(...); matrix constructed from the two vectors through a loop.

Eigen::MatrixXd qzMatrix(...); uses the xjk matrix to construct a new one using a probability density function, element by element.

Eigen::MatrixXd q1zMatrix(...); uses the xjk matrix too, to construct a new one using a probability density function, element by element.

Eigen::MatrixXd qjkMatrix(...); combination of the qz and the grid, element by element loop.

Eigen::MatrixXd q1jkMatrix(...); combination of the qz, q1z and the grid, element by element loop.

Eigen::MatrixXd mjkMatrix(...); sums elements from qjk and q1jk, element by element loop.

Eigen::MatrixXd globalMatrix(...); loops all the above functions (120 times generally) except the grid, which is fixed, and multiplies the 120 mjk matrices to obtain a global one.

一个全局矩阵 200x200 大约需要 20 秒的计算时间,500x500 大约需要 200 秒。如何让我的代码 运行 更快,并优化我的矩阵乘法? (我试过稀疏矩阵,但是用的时间更长)

我正在使用 MinGW64。

确保编译时进行了全面优化,例如g++ -O3 -DEIGEN_NO_DEBUG 如果使用 g++。此外,通过 OpenMP 打开并行化可能会有所帮助,在编译和链接时使用 -fopenmp

我使用以下代码编译大多数 Eigen 代码(使用 g++):

g++ -I/path/to/eigen -O3 -DEIGEN_NO_DEBUG -fopenmp program.cpp