在上一篇博客中,我们讨论了如何记录Matlab程序运行过程中所占用的最大内存。
博客原文:如何记录Matlab程序运行过程中所占用的最大内存-CSDN博客
但经过测试发现,这与实际有非常大的差异。运行如下例子:
clear;clc;
profile on -memory
cnt = 0;
user = memory;
MemUsed_now = user.MemUsedMATLAB;
cnt = cnt + 1;
disp(['[cnt=',num2str(cnt), '] Mem = ',num2str(MemUsed_now/1024/1024/1024)]);
X1 = randn(20000);
user = memory;
MemUsed_now = user.MemUsedMATLAB;
cnt = cnt + 1;
disp(['[cnt=',num2str(cnt), '] Mem = ',num2str(MemUsed_now/1024/1024/1024)]);
X2 = randn(20000);
user = memory;
MemUsed_now = user.MemUsedMATLAB;
cnt = cnt + 1;
disp(['[cnt=',num2str(cnt), '] Mem = ',num2str(MemUsed_now/1024/1024/1024)]);
profile report
p = profile('info');
profile off
fullpath = mfilename('fullpath');
%[path, name, ~] = fileparts(fullpath);
fullname = [fullpath, '.m'];
for i=1:length(p.FunctionTable)
if strcmp(fullname,p.FunctionTable(i).FileName)
idx_file = i;
break;
end
end
PeakMem = p.FunctionTable(idx_file).PeakMem;
TotalMem = p.FunctionTable(idx_file).TotalMemAllocated;
disp(['PeakMem = ', num2str(PeakMem/1024/1024/1024)]);
disp(['TotalMem = ', num2str(TotalMem/1024/1024/1024)]);
程序中我使用了memory命令在多个位置记录当前使用的内存,同时也使用了profile on -memory命令实时记录内存使用情况。profile report输出结果如下:
程序输出结果如下:
[cnt=1] Mem = 1.5756
[cnt=2] Mem = 4.5557
[cnt=3] Mem = 7.5292
PeakMem = 2.986
TotalMem = 5.9718
这个程序主要是生成了两个20000*20000的矩阵。在Matlab中,一个浮点类型数据是占8个字节,因此程序中的X1和X2各占3200000000个字节。这个数字除以三次1024,大概是2.9802GB。可以看到,profile记录的峰值内存是2.986GB,这很明显是有问题的,因为程序中有两个20000*20000的矩阵,这就接近4GB了。而三次使用memory记录的内存使用显示,占用的内存最多时有7.5292GB,这也是一个合理的数字。
程序中我还看了分配的内存(TotalMemAllocated字段),显示是TotalMem = 5.9718GB,这个虽然低于memory记录的结果,但也是比较合理的。经过一些更复杂的程序测试,这个应该是累积分配的内存,所以有的时候会比实际占用的最大内存要大上好几倍。
又迷茫了,还是不知道如何在不对程序进行大量修改(即插入memory)的前提下记录程序使用的最大内存。