I have written simple C++ code and tested it in C++, then I have adapted the same code for MATLAB by mex file_name.cpp
and run the same code in MATLAB which is using the same compiler as C++. Here is the code:
int k;
for(int j = 0; j < 100;j++){
for(int i = 0; i < 10000000; i++){
k++;
}
k/=10000000
}
Here is MATLAB code:
double a;int j;int i;
double* k;
for(j = 0; j < 100;j++){
for(i = 0; i < 10000000; i++){
a = a+1;
}
a = a / 10000000;
}
plhs[0] = mxCreateDoubleMatrix(1,1,mxREAL);
k = mxGetPr(plhs[0]);
*k = (double)a;
I have edited this code for MATLAB, i.e changing to suitable types, adding MEX-function etc and the results are approx 900ms in MATLAB as opposed to 3100 ms in C++.
What I don't understand is both are running the same code and with the same compiler (in MATLAB I write mex -setup
in command line and selected Visual Studio compiler as MEX compiler), however, MATLAB is around 3.5 times faster.
What is MATLAB doing to be that faster and what is C++ not doing? Could somebody please explain me why there is so huge difference? I have tried some other codes, all are 3-6 times faster in MATLAB.
My PC is 64-bit Windows 7, Visual Studio 2010 is used for C++, MATLAB is R2012b.
Is it possible this is because of my Visual Studio version? If I change it to VS2012, would it be faster?
mex -v output is here.
Thanks,