求解矩阵方程耗时比较(直接求逆,Qr分解,LU分解)

测试环境:

  1. C++
  2. Egien库

代码

#include <iostream>
#include <ctime>
using namespace std;
#include <windows.h>
#include<Eigen/Core>
#include<Eigen/Dense>
#define MATRIX_SIZE 50
using namespace Eigen;

int main()
{
    Matrix< double, MATRIX_SIZE, MATRIX_SIZE > matrix_NN;
    matrix_NN = MatrixXd::Random( MATRIX_SIZE, MATRIX_SIZE );
    Matrix<double, MATRIX_SIZE, 1> v_Nd;
    v_Nd = MatrixXd::Random( MATRIX_SIZE,1);
    clock_t time_stt = clock();

    //直接求逆
    Matrix< double, MATRIX_SIZE, 1> x = matrix_NN.inverse()*v_Nd;
    cout << "time useing normal inverse is " << 1000.0 * (clock() - time_stt) / 
                            (double)CLOCKS_PER_SEC << "ms" << endl;
    //Qr分解
    time_stt = clock();
    x = matrix_NN.colPivHouseholderQr().solve(v_Nd);
    cout << "time use in Qr composition is " << 1000 * (clock() - time_stt) / (double)
        CLOCKS_PER_SEC << "ms" << endl;

    //LU分解
    time_stt = clock();
    x = matrix_NN.partialPivLu().solve(v_Nd);
    cout << "time use in LU composition is " << 1000 * (clock() - time_stt) / (double)
        CLOCKS_PER_SEC << "ms" << endl;

    system("pause");
}

 结果

因为矩阵是随机的,所以每次运行的结果都不一样,最差的时候有可能,求逆的速度是Qr分解的5-6倍,有时候可能也只会相差10ms左右。
但运行速度从快到慢为:
LU分解 > Qr分解 > 求逆

猜你喜欢

转载自blog.csdn.net/renhaofan/article/details/80740697