Why adding a subfunction breaks an unrelated in-place function call?
4 views (last 30 days)
Show older comments
Debugging some memory issues in my code, I reduced the problem into this test. This works as I expect:
function inplaceTest
x = randn(2^28, 1);
tic, y = f(x); toc % Argument copied - Elapsed time is 0.488432 seconds.
tic, x = f(x); toc % In-place call - Elapsed time is 0.000304 seconds.
end
function x = f(x)
x(50) = 0;
end
But adding a nested subfunction, even a dummy one, somehow breaks the in-place operation:
function inplaceTest2
x = randn(2^28, 1);
tic, y = f(x); toc % Argument copied - Elapsed time is 0.497300 seconds.
tic, x = f(x); toc % Takes even longer? - Elapsed time is 0.686611 seconds.
function dummy()
end
end
function x = f(x)
x(50) = 0;
end
The ordering of the function calls does not seem to matter.
What is going on here? Does this mean that in-place operations are disabled in functions that have subfunctions?
0 Comments
Answers (1)
Jan
on 12 Mar 2021
You can check with
format debug
if the variable is copied or re-used. Does the pointer to the data change?
I guess, that the JIT cannot work reliably if a nested function might interfere. Therefore I avoid nested functions in general.
2 Comments
Jan
on 12 Mar 2021
The decision to use nested function cannot be undone by setting a magic flag. As long, as Matlab's JIT accelerator cannot handle nested structs efficiently, there is no chance to solve this. Ask the MathWorks team for an enhancement of the JIT. This will take at least a year until it is implemented.
See Also
Categories
Find more on Parallel Computing Toolbox in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!