why mexw64 generated by coder runs slower than pure .m file?
Ältere Kommentare anzeigen
I'm recently learning how to use mex files. The case that I try to reproduce is from https://www.youtube.com/watch?v=TAKjSi-77Ns&list=PLcgIaTuuWp3kWI8d1C1wZDl0SfQDxm-CK&index=61. I tried to verify that mexw64 file genrated by coder runs faster than .m file.To my surprise, I followed the the lesson step by step, but the result was inconsistent. Here is the function:
function Sum = SUModd(N)
%#codegen
Sum=0; count=1;
while ne(count,N)
if ne(mod(count,2),0)
Sum=Sum+count;
else
Sum=Sum;
end
count=count+1;
end
end
Then I generated mexw64 file following the instructions, compared the execution time between the .m file and the .mexw64 file:
%% test the consuption time
clear all;
N=1e8;
t = cputime;
SUModd(N)
Tmat = cputime-t;
fprintf('M-file comp. Time is %5.5f sec \n',Tmat);
%% mex function generated from coder
T_mex = cputime;
SUModd_mex(N)
TT = cputime-T_mex;
fprintf('Mex-file comp. Time is %5.5f sec \n',TT);
the result confused me because mexw64 cost more time than pure matlab file which is inconsistent with video:
M-file comp. Time is 9.71875 sec
Mex-file comp. Time is 9.75000 sec
To find out what go wrong,I rewrite the SUModd function in C, and mex it:
#include "mex.h"
double summation(double N) {
// double N=1e8;
double sum = 0;
int cout = 1;
while (cout != N) {
if ((cout % 2) != 0) {
sum = sum + (double)cout;
}
else {
sum = sum;
}
cout = cout + 1;
// printf("%d \n",cout);
}
return sum;
}
void mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[])
{
double x,result;
if (nrhs != 1)
mexErrMsgTxt("Wrong number of input arguments.\n");
// 检查输入变量数量是否正确,否则报错
if (nlhs > 1)
mexErrMsgTxt("Too many output argumnents.\n");
x = mxGetScalar(prhs[0]);
// result = summation(x);
double *finaldata;
plhs[0] = mxCreateDoubleMatrix(1,1,mxREAL);
finaldata = mxGetPr(plhs[0]);
finaldata[0] = summation(x);
}
the time consuption was just 0.12500 sec which was consistent with the video.
So my question is: Why the mexw64 file generated by coder didn't improve the computational efficiency? Or Did I missed some details when I ws using coder?
Akzeptierte Antwort
Weitere Antworten (0)
Kategorien
Mehr zu MATLAB Coder finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

