Matlab new C++ MEX function runnign speed vs C Mex interfaces
Recently I am working on boosting Matlab project performances. As you may know, Matlab 2017 introduced a new C++ Mex function to avoid unnecessary data copies, I believe it supposes to be faster than previous C Mex interfaces. So I wrote a demo to test, this demo simply calculates returns for some 2d matrix, and for 50 rounds iterations, C++ MEX took 70s to complete vs 0.089s C Mex function. I am using Matlab 2021b and visual studio 2022. This runtime is unreasonable
Sample Matlab code:
ret(di,:) = basedata(di,:) ./ (basedata(di-1,:) * flag(di:, );
So I converted this function for both c mex and c++ mex function: c++ mex:
size_t numRows = inputs[0].getDimensions()[0];
size_t numColumns = inputs[0].getDimensions()[1];
TypedArray<double> ret = std::move(inputs[0]);
TypedArray<double> data = inputs[1];
TypedArray<double> flag = inputs[2];
size_t i, j, pos;
for (i = 1; i < numRows; i++) {
for (j = 0; j < numColumns; j++) {
if (data[i - 1][j] > 1 && data[i][j] > 1)
ret[i][j] = (data[i][j] / data[i - 1][j] - 1.0) * flag[i][j];
}
}
outputs[0] = ret;
C MEX:
double *ret = mxGetPr(prhs[0]);
double *data = mxGetPr(prhs[1]);
double *flag = mxGetPr(prhs[2]);
size_t ROWS = mxGetM(prhs[0]);
size_t COLS = mxGetN(prhs[0]);
for (j = 0; j < COLS; j++) {
for (i = 1; i < ROWS; i++) {
pos = j * ROWS + i;
if (data[pos - 1] > 1 && data[pos] > 1)
ret[pos] = (data[pos] / data[pos - 1] - 1.0) * flag[pos];
}
}
And I also did some future testing, in C Mex function matrix[i,j] converted into j*Rows +i, however in C++ interface we can use matrix[i][j] to index, So I believe it has issues with the operator overloading. And if I use below C++ Mex iterator the speed is almost identical with C Mex function.
for (auto &elem: ret) {
elem = 1;
}
In my scenario, I am unable to use iterator like this. Can someone explain why?
Comments
Post a Comment