||
Matlab2017a版本,编写for循环程序时,经常提示对变量进行preallocation memory(预设内存)的提示,在matlab自带帮助文档中,有如下具体解释,同时提供了实例:用zeros或ones函数预定义变量。
for
and while
loops that incrementally increase the size of a data structure each time through the loop can adversely affect performance and memory use. Repeatedly resizing arrays often requires MATLAB® to spend extra time looking for larger contiguous blocks of memory, and then moving the array into those blocks. Often, you can improve code execution time by preallocating the maximum amount of space required for the array.
The following code displays the amount of time needed to create a scalar variable, x
, and then to gradually increase the size of x
in a for
loop.
If you preallocate a 1-by-1,000,000 block of memory for x
and initialize it to zero, then the code runs much faster because there is no need to repeatedly reallocate memory for the growing data structure.
Use the appropriate preallocation function for the kind of array you want to initialize:
zeros
for numeric arrays
cell
for character arrays
另有中文资料(来自ilovematlab网站)特别推荐 for n = len : -1 :1 的这种for循环写法,即不需要zeros() 之类的先开内存,也可以达到预分配内存的效果。该网页也列举了matlab内存管理机制的内容,如下:
主要的问题来自于matlab的内存管理机制:
对于一个数组,matlab先在内存中找一块放得下的连续空间,如果这个数组一直增大到那个连续空间放不下了,matlab会去找另外一个放得下的连续空间(好像记得在什么地方听到过是找一个原来内存2倍大的地方),这样就带来2个问题:
1. 额外的操作,找内存 + 复制; 而且这种操作有可能是很多次。
2. 额外的空间,这个时候有2份copy在内存中。导致内存不足的常见原因之一
网页最后提供了两个实例,考虑博文长度,本文未重复列出。
Archiver|手机版|科学网 ( 京ICP备07017567号-12 )
GMT+8, 2024-11-23 00:38
Powered by ScienceNet.cn
Copyright © 2007- 中国科学报社