在测试是否any()短路时(确实如此!)我在预分配测试变量时发现了以下有趣的行为:
test=zeros(1e7,1);
>> tic;any(test);toc
Elapsed time is 2.444690 seconds.
>> test(2)=1;
>> tic;any(test);toc
Elapsed time is 0.000034 seconds.
Run Code Online (Sandbox Code Playgroud)
但是,如果我这样做:
test=ones(1e7,1);
test(1:end)=0;
tic;any(test);toc
Elapsed time is 0.642413 seconds.
>> test(2)=1;
>> tic;any(test);toc
Elapsed time is 0.000021 seconds.
Run Code Online (Sandbox Code Playgroud)
事实证明,这是因为变量在完全填充信息之前并不真正在RAM上,因此第一次测试需要更长时间,因为它需要分配它.我检查这个的方法是查看Windows任务管理器中使用的内存.
虽然这可能有些意义(不要在需要之前进行初始化),但让我更加困惑的是下面的测试,其中变量填充在for循环中,并且在某些时候执行被停止.
test=zeros(1e7,1);
for ii=1:1e7
test(ii)=1;
if ii==1e7/2
pause
end
end
Run Code Online (Sandbox Code Playgroud)
在检查MATLAB使用的内存时,我可以看到当停止时,它只使用了50%的test所需内存(如果已满).这可以用不同的记忆百分比再现.
有趣的是,以下内容也没有分配整个矩阵.
test=zeros(1e7,1);
test(end)=1;
Run Code Online (Sandbox Code Playgroud)
我知道MATLAB不是动态分配和增加test循环的大小,因为这会使结束迭代非常慢(由于需要高memcopys),并且它也会在我提出的最后一次测试中分配整个数组.所以我的问题是:
到底是怎么回事?
有人建议这可能与虚拟内存和物理内存有关,并且与操作系统看待内存的方式有关.不知道如何链接到这里提出的第一个测试.任何进一步的解释都是理想的.
赢得10 x64,MATLAB 2017a