MEX Function c++ vs c interface running speed

Hi Team,
Recently I am working on boosting our matlab code performance. The old c mex API works good and I noticed that matlab 2018 introduced a new c++ mex function to avoid data copy. I believe it suppose to be faster but in my code the performance is pretty bad for C++ mex function.
I tested in my local env c++ mex code need 70s for my test data about 50 rounds iteration, but c mex only took 0.089s total. In my test I know in C++ mex the iteration is not optimized but in my scenario I am unable to use sample code iterator (auto& elem : inMatrix) .
Can someone help explain? Thanks in advance
Sample 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> tradable = 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 *tradable = mxGetPr(prhs[2]);
size_t ROWS = mxGetM(prhs[0]);
size_t N_INSTRUMENTS = mxGetN(prhs[0]);
for (j = 0; j < N_INSTRUMENTS; 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];
}
}

3 个评论

700 times slower ? Are you sure about those numbers? That sounds surprisingly bad, doing for-loop with MATLAB will not be that bad.
Yes, i think the matrix[i][j] overload has some issues. If I only do iteration like below, the speed is almost identical as c mex function. But there is no guidance about how to index 2d array faster in C++ mex.
for (auto &elem: ret) {
elem = 1;
}
That why I never like C++; all the inner details are hiden to user.

请先登录,再进行评论。

回答(0 个)

类别

帮助中心File Exchange 中查找有关 Matrix Indexing 的更多信息

产品

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by