Sharing large structure with nested functions with function handles increase main function overhead?
9 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Good day!
I am building a large simulation model using matlab. I have a quite complitcated structure with many sub structures and data containing model states and I have found that much of the computational power is spent on shuffeling this structure to and from functions where I edit the model states. I decided to try out some nested functions that share this complicated structure, so no copying is necessary. However, the nested functions seem to incur a massive overhead charge, using just one nested function increases the self execution time ('end' in profiler) to 60% of the main function, this is compeared to using a .m file function insted of nested.
Some relevant information:
I'm calling the function from a for loop a couple of thousand of times 4000-6000.
I'm using function handles in a cell array and calling them like so: Output = cell_array{i}(Input);
The shared structure is modified several times inside the for loop by different functions that are specified in m-files.
The nested function seems to execute faster than the .m function, but the total execution time is around 100% slower.
Is there something that can explain this increase in overhead? It would be a massive improvement not having to copy data between functions so I would very much appricieta some input!
Thanks!
3 Commenti
Stephen23
il 17 Nov 2023
"I have a quite complitcated structure with many sub structures and data containing model states and I have found that much of the computational power is spent on shuffeling this structure to and from functions where I edit the model states."
Flatter data is often much more efficient to process than deeply nested data. It usually makes code simpler too.
"It would be a massive improvement not having to copy data between functions so I would very much appricieta some input!"
MATLAB does not copy data every time you pass something to a function. Search this forum for "copy on write" to know how it really works, as well as reading this documentation:
Risposta accettata
Matt J
il 17 Nov 2023
where I edit the model states
It is the editing of the variable contents that incurs time, not the passing of them to functions. Note that if one of the struct variables is a large numeric matrix, changing even one element will allocate memory for a complete new matrix. Similarly, if you have lots of small matrices that you are making changes to, that would consume a lot of time as well.
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Numeric Types in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!