opencv 矩阵相乘, matlab矩阵相乘,以及自己写的矩阵相乘的时间比较

来源:互联网 发布:淘宝上的天王表旗舰店 编辑:程序博客网 时间:2024/05/21 06:25

直接上代码吧

matlab

clc
close all
clear all


tic; c = rand(7500,7500)*rand(7500,1);toc;
Elapsed time is 2.576807 seconds.


 

opencv code


#include <cv.h>
#include <highgui.h>
#include <stdio.h>
#include <iostream>
using namespace std;


#pragma comment( lib, "cxcore.lib" )
#pragma comment( lib, "cvaux.lib" )
#pragma comment( lib, "highgui.lib" )
#pragma comment( lib, "cv.lib" )
void GenRand(CvMat* arr, int seed);

void main()
{
    int rows,temp_cols,cols;
    rows = 7500;temp_cols=7500,cols=1;
  

    /*CvMat* mat1 = cvCreateMat(rows,temp_cols,CV_32FC1);
    CvMat* mat2 = cvCreateMat(temp_cols,cols,CV_32FC1);
   
    for(int i=0;i<rows;i++)
    {
        for(int j=0;j<temp_cols;j++)
        {
            cvmSet(mat1,i,j,1);
        }
    }


    for(int i=0;i<temp_cols;i++)
    {
        for(int j=0;j<cols;j++)
        {
            cvmSet(mat2,i,j,2);
        }
    }*/

    int seed = 3;
    CvMat* mat1 = cvCreateMat(rows,temp_cols,CV_32FC1);
    CvMat* mat2 = cvCreateMat(temp_cols,cols,CV_32FC1);
    GenRand(mat1, seed); //调用
    GenRand(mat2, seed); //调用


    CvMat* mat3 = cvCreateMat(rows,cols,CV_32FC1);

    int64 start_Time,end_Time;
    double elapsed_seconds, tickspersecond=cvGetTickFrequency()*1.0e6;


    start_Time = cvGetTickCount(); 


    cvMatMul(mat1,mat2,mat3);


    end_Time = cvGetTickCount();


    elapsed_seconds = (double)(end_Time - start_Time)/tickspersecond;


    cout<<" elapsed_seconds = "<<elapsed_seconds<<" s "<<endl;


    for(int i=0;i<cols;i++)
    {
        for(int j=0;j<rows;j++)
        {
            cout<<" "<<cvmGet(mat3,i,j)<<" ";
        }
        cout<<endl;
    }


}

void GenRand(CvMat* arr, int seed)
{
    // let's noisy_screen be the floating-point 2d array that is to be "crapped"
    CvRandState rng;

    // initialize random generator
    rng.state = cvRNG(0xffffffff);
    cvRandInit( &rng,
        0, 1,      // use dummy parameters now and adjust them further
        seed, // use input seed here
        CV_RAND_UNI // specify uniform type
        );
    //用随机数填充矩阵
    cvRandArr( &rng.state, arr, CV_RAND_UNI, cvRealScalar(0), cvRealScalar(1) );
    // RNG state does not need to be deallocated
}


 

结果是在release下的0.123289s, 区别快20倍了,看样子还是opencv的快。

我自己写的矩阵相乘的code更慢,看样子opencv和matlab都做了下优化。
但是你的这2个矩阵相乘要是有一些规律的话,那么matlab可能是最快的,毕竟matlab对于矩阵的操作有很多的优化算法