필터 지우기
필터 지우기

Avoid Copies of Large Arrays doesn't work (c++)

조회 수: 2 (최근 30일)
Or Nahir
Or Nahir 2018년 4월 26일
답변: Or Nahir 2018년 5월 1일
Hi,
I'm trying to write a simple function to verify that my c++ code won't copy large arrays, like in this example:
I wrote the following function:
#include "mex.hpp"
#include "mexAdapter.hpp"
class MexFunction : public matlab::mex::Function {
public:
void operator()(matlab::mex::ArgumentList outputs, matlab::mex::ArgumentList inputs) {
matlab::data::TypedArray<double> x = std::move(inputs[0]);
x[0] = 2;
outputs[0] = x;
}
};
It seems to run very slow, so I'm guessing it is because of data being copied.
>> x = rand(1e8,1);
>> tic; x = example(x) ; toc;
Elapsed time is 0.664293 seconds.
>> tic; x(1) = 2 ; toc;
Elapsed time is 0.000065 seconds.
Any ideas?
Thanks!

채택된 답변

Or Nahir
Or Nahir 2018년 5월 1일
So it does seem to work after all. The problem is that Matlab does operation in place only if the the code is in a function and not a script.
For example, we see that the current Matlab cumsum function doesn't change pr address (use 'format debug' to print variable memory address):
function test()
x = rand(5,1)';
x
x = cumsum(x);
x
end
x =
Structure address = 13c05ce20
m = 1
n = 5
pr = 600001cad9a0
0.3727 0.5964 0.5954 0.7112 0.4096
x =
Structure address = 13c05cfe0
m = 1
n = 5
pr = 600001cad9a0
0.3727 0.9691 1.5646 2.2758 2.6853
But if we do the same in a script we get:
x = rand(5,1)';
x
x = cumsum(x);
x
Structure address = 13c0453d0
m = 1
n = 5
pr = 6000010aaac0
0.2368 0.5640 0.9127 0.7092 0.7476
x =
Structure address = 13c047f90
m = 1
n = 5
pr = 600002c89de0
0.2368 0.8008 1.7136 2.4228 3.1704
This behaviour is only true for in place functions. For non in place function the address of the output array is always different.
So, the last thing to check is to see that my example function acts in place inside a function:
function test()
x = rand(5,1)';
x
x = example(x, 0);
x
Structure address = 13c047270
m = 1
n = 5
pr = 600001eb3580
0.1054 0.9719 0.8674 0.7342 0.1795
x =
Structure address = 13c046940
m = 1
n = 5
pr = 600001eb3580
2.0000 0.9719 0.8674 0.7342 0.1795

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Call C++ from MATLAB에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by