Why adding a subfunction breaks an unrelated in-place function call?

4 visualizaciones (últimos 30 días)
Niilo Sirola
Niilo Sirola el 12 de Mzo. de 2021
Comentada: Jan el 12 de Mzo. de 2021
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?

Respuestas (1)

Jan
Jan el 12 de Mzo. de 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 comentarios
Niilo Sirola
Niilo Sirola el 12 de Mzo. de 2021
Yes the pointer to x changes on those calls that take ~0.5s. I guess the same here, but would prefer to find a solution that does not require massive rewrite of the code to work without nested functions...
Jan
Jan el 12 de Mzo. de 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.

Iniciar sesión para comentar.

Categorías

Más información sobre Parallel Computing Toolbox en Help Center y File Exchange.

Productos


Versión

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by