MEX Function c++ vs c interface running speed

6 visualizaciones (últimos 30 días)
Xuechao Qin
Xuechao Qin el 19 de Abr. de 2022
Editada: Xuechao Qin el 21 de Abr. de 2022
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 comentarios
Xuechao Qin
Xuechao Qin el 19 de Abr. de 2022
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 el 19 de Abr. de 2022
That why I never like C++; all the inner details are hiden to user.

Iniciar sesión para comentar.

Respuestas (0)

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by