MEX Function c++ vs c interface running speed

조회 수: 6 (최근 30일)
Xuechao Qin
Xuechao Qin 2022년 4월 19일
편집: Xuechao Qin 2022년 4월 21일
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
Xuechao Qin
Xuechao Qin 2022년 4월 19일
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;
}
Bruno Luong
Bruno Luong 2022년 4월 19일
That why I never like C++; all the inner details are hiden to user.

댓글을 달려면 로그인하십시오.

답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by