How to save memory: loops or copy paste

13 vues (au cours des 30 derniers jours)
Lucius
Lucius le 13 Mai 2015
Modifié(e) : Joseph Cheng le 13 Mai 2015
I am wondering how one can save precious RAM in order to be able to handle larger arrays or more complex stuff.
Which uses less memory: using a loop to repeat a code (e.g.) three times or to copy the respective code three times in a row?

Réponse acceptée

James Tursa
James Tursa le 13 Mai 2015
Modifié(e) : James Tursa le 13 Mai 2015
The memory used by the code itself is insignificant, so looping vs copy-paste is not a memory concern. For maintainability and readability, a loop would be far preferable ... or vectorize the loop if possible.
If you are having memory issues we would need to see your code before we could offer specific advice on how to decrease memory usage. Vectorization can often bring both speed and memory benefits, but it depends on what the code is doing.
  1 commentaire
Joseph Cheng
Joseph Cheng le 13 Mai 2015
Modifié(e) : Joseph Cheng le 13 Mai 2015
If your GPU has CUDA cores you maybe able to utilize them
http://www.cac.cornell.edu/matlab/TechDocs/Examples/BestPracticesGPU.aspx may give you an idea on what you can utilize the GPU for

Connectez-vous pour commenter.

Plus de réponses (1)

Walter Roberson
Walter Roberson le 13 Mai 2015
To reduce memory usage, pre-allocate the output arrays to avoid growing them as you go.
Code repeated multiple times will take more space in the MATLAB interpreter than a loop would take, unless perhaps the code was nearly trivial. However, repeating code multiple times can be more efficient than looping.
You should consider using single precision instead of double precision. If you do that, make sure that any constants you use in the code do not accidentally change the precision of the calculation.
But mostly... get more RAM and a 64 bit version of MATLAB. Memory is too inexpensive these days to make it worth the time it takes to use the minimum amount of memory -- not unless you are creating code to go into a limited-resource embedded system.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Tags

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by