(重新发布,因为我没有得到任何满意的答案,而且看起来没人关心它了)这是问题所在
考虑以下函数:
function A = plodding(N,d)
for ii = 1:N
jj = 1;
A(ii,jj) = randn;
while abs(A(ii,jj)) < d
jj = jj + 1;
A(ii,jj) = randn;
end
end
重写此函数以消除减慢它的分配问题。调用新功能,巡航。在具有 7.8 GB 可用内存的戴尔 Latitude E6410 上,消除分配问题会产生 7 倍的加速因子。
这是我的工作:
带有 rng(0) 的原始版本
function A = plodding(N,d)
rng(0); % To compare between the original and the modified version
for ii = 1:N
jj = 1;
A(ii,jj) = randn;
while abs(A(ii,jj)) < d
jj = jj + 1;
A(ii,jj) = randn;
end
end
end
修改后的版本
function A = cruising(N,d)
rng(0);
for jj = 1:N % Reorganize, so elems are added column-wise
ii = 1;
A(ii,jj) = randn;
while abs(A(ii,jj)) < d
ii = ii + 1;
A(ii,jj) = randn;
end
end
A = A'; % To get the matrix desired
end
但是当我测试时(请仔细查看结果以理解我的问题)
>>tic;A = plodding(10000,2);toc
Elapsed time is 9.289355 seconds.
>>tic;A1 = cruising(10000,2);toc;
Elapsed time is 0.078783 seconds.
>>
>>tic;A = plodding(5,5);toc
Elapsed time is 1.168961 seconds.
>> tic;A1 = cruising(5,5);toc;
% When I posted this thread, it's already more than 10 mins and MATLAB's still "busy"!
根据我从课程中学到的知识,我的逻辑应该是正确的,因为 MATLAB 按列存储元素。因此,在任何情况下(无论 N 小还是大,d 小还是大),在任何情况下,巡航都应该比缓慢行驶更快。MATLAB 的这种行为表明我仍然不太了解它。有人可以帮帮我吗???