How would I reduce overhead in mex function?
4 次查看(过去 30 天)
显示 更早的评论
I want to know how to speed up mex function.
I checked the time of same c program of matrix-vector product, comparing to matlab-mex and without matlab.
the below is mex file program.
#include "mex.h"
#include "math.h"
/* The computational routine */
void MatPro(double *x, double *y, double *z, mwSize m, mwSize n)
{
int i;
int j;
/* main program */
for(i=0;i<m;i++){
z[i]=0;
for(j=0;j<m;j++){
z[i]=z[i]+x[m*j+i]*y[j];
}
}
}
/* The gateway function */
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
double *in1; /* input scalar */
mwSize n; /* size of matrix */
mwSize m;
double *in2;
double *out; /* output matrix */
/* get the value of the input */
in1 =mxGetPr(prhs[0]);
/* create a pointer to the real data in the input matrix */
in2 =mxGetPr(prhs[1]);
/* get dimensions of the input matrix */
m = (mwSize)mxGetM(prhs[1]); //GYO
n = (mwSize)mxGetN(prhs[1]); //RETU
/* create the output matrix */
plhs[0] = mxCreateDoubleMatrix(m,n,mxREAL);
/* get a pointer to the real data in the output matrix */
out = mxGetPr(plhs[0]);
/* call the computational routine */
MatPro(in1,in2,out,m,n);
}
I experienced using the file in matlab. Also I checked the time.
M=rand(32768);
x=rand(32768,1);
tic;
y=MatPro(M,x);
toc;
Second, c program of matrix-vector product is below
#include "stdio.h"
#include "time.h"
#include "math.h"
#include "stdlib.h"
#include "omp.h"
void matVec(long *ans1, long *ans2)
{
// set variables
int m=32768;
int n=1;
int* x;
int* y;
int* z;
struct timespec startTime, endTime;
// set matrix
x=(int *)malloc(sizeof(int) * m*m);
y=(int *)malloc(sizeof(int) * m*n);
z=(int *)malloc(sizeof(int) * m*n);
// set value
for (i=0;i<m*n;i++) {
x[i]=rand();
y[i]=rand();
}
// check start time
clock_gettime(CLOCK_REALTIME, &startTime);
// calculation
for(i=0;i<m;i++){
z[i]=0;
for(j=0;j<m;j++){
z[i]=z[i]+x[m*i+j]*y[j];
}
}
// check end time
clock_gettime(CLOCK_REALTIME, &endTime);
// output
if (endTime.tv_nsec < startTime.tv_nsec) {
*ans1=endTime.tv_sec - startTime.tv_sec - 1;
*ans2=endTime.tv_nsec + (long int)1.0e+9 - startTime.tv_nsec;
} else {
*ans1=endTime.tv_sec - startTime.tv_sec;
*ans2=endTime.tv_nsec - startTime.tv_nsec;
}
}
int main(void){
long *ans1;
long *ans2;
printf("dimension = %09d, time = ",m);
matVec(&ans1,&ans2);
printf("%5ld.%09ld",ans1,ans2);
printf(" (sec)\n");
return 0;
}
I used the file without matlab to compare time.
I used Macbook Pro (intel core i7, 2.5GHz, 16GBmemory, macOS High sierra ver 10.13.1). The compiler is clang 5.0.0. I didn't use compiler option. Matlab is 2017R version.
The result is
- matrix-vector product c file with Matlab is 44.0157 sec,
- matrix-vector product c file without matlab is 3.927542 sec
How can I reduce overhead of mex function in Matlab??
回答(0 个)
另请参阅
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!