正如标题说的那样,我想知道Matlab在这两个选项之间有什么不同。为了便于论证,假设矩阵a和idx足够大,足以处理内存问题,并定义:
a(idx) = []a = a(~idx)我的直觉说,如果A执行值重新分配,那么CPU需要处理从原始位置到新的有序位置的索引副本,同时跟踪相同矩阵的当前“头”,然后再修剪多余的内存。
另一方面,案例B将对新分配的内存空间执行索引大容量复制。
因此,情况A可能比案例B慢,但内存要求较低。我的假设是对的吗?我不知道,写完这封信后我觉得案子B需要先做A案.有什么想法吗?
提前感谢
发布于 2016-10-20 09:50:38
这很有趣,所以我决定采取如下措施:
我正在使用Windows (64位)版本的Matlab R2016a。
CPU:内核i5-3550,3.3GHz。内存: 8GB DDR3 1333 (双通道)。
len = 100000000; %Number of elements in array (make it large enouth to be outsize of cache memory).
idx = zeros(len, 1, 'logical'); %Fill idx with ones.
idx(1:10:end) = 1; %Put 1 in every 10'th element of idx.
a = ones(len, 1); %Fill arrary a with ones.
disp('Measure: a(idx) = [];')
tic
a(idx) = [];
toc
a = ones(len, 1);
disp(' ');disp('Measure: a = a(~idx);')
tic
a = a(~idx);
toc
disp(' ');disp('Measure: not_idx = ~idx;')
tic
not_idx = ~idx;
toc
a = ones(len, 1);
disp(' ');disp('Measure: a = a(not_idx);')
tic
a = a(not_idx);
toc结果:
Measure: a(idx) = [];
Elapsed time is 1.647617 seconds.
Measure: a = a(~idx);
Elapsed time is 0.732233 seconds.
Measure: not_idx = ~idx;
Elapsed time is 0.032649 seconds.
Measure: a = a(not_idx);
Elapsed time is 0.686351 seconds.结论:
a = a(~idx)的速度大约是a(idx) = []的两倍。a = a(~idx)的总时间等于not_idx = ~idx加a = a(not_idx)之和
Matlab可能是单独计算~idx,因此它消耗了更多的内存。
内存消耗表只有在物理内存完全消耗时才能使用。
我认为这是可以忽略不计的(~idx内存消耗是暂时的)。https://stackoverflow.com/questions/40135620
复制相似问题