天水一色分享 http://blog.sciencenet.cn/u/lincystar

博文

Matlab编程之预分配内存

已有 11413 次阅读 2018-1-9 16:40 |系统分类:科研笔记| matlab编程, 高效计算, 预设内存

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.

ticx = 0;for k = 2:1000000   x(k) = x(k-1) + 5;endtoc
Elapsed time is 0.301528 seconds.

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.

ticx = zeros(1, 1000000);for k = 2:1000000   x(k) = x(k-1) + 5;endtoc
Elapsed time is 0.011938 seconds.

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在内存中。导致内存不足的常见原因之一

网页最后提供了两个实例,考虑博文长度,本文未重复列出。




https://blog.sciencenet.cn/blog-237238-1093951.html

上一篇:matlab 主成分分析warning
下一篇:摘抄:顾炎武 《与友人书》
收藏 IP: 36.149.1.*| 热度|

0

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-12-23 01:11

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部