为代码的效率重新组织循环(重新发布,之前没有令人满意的答案!)

时间:2015-08-01 21:16:42

标签: matlab coding-efficiency

(重新发布,因为我没有得到任何令人满意的答案,看起来没有人关心它了) 这就是问题

考虑以下功能:

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

重写此函数以消除减慢分配问题的速度。调用新功能,巡航。戴尔Latitude E6410具有7.8千兆字节的可用内存,消除了分配问题,因此产生了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的这种行为表明我仍然不太了解它的某些内容。有人可以帮帮我???

0 个答案:

没有答案