How to save memory: loops or copy paste
조회 수: 12 (최근 30일)
이전 댓글 표시
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?
댓글 수: 0
채택된 답변
James Tursa
2015년 5월 13일
편집: James Tursa
2015년 5월 13일
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
Joseph Cheng
2015년 5월 13일
편집: Joseph Cheng
2015년 5월 13일
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
추가 답변 (1개)
Walter Roberson
2015년 5월 13일
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.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!