在Octave 4.0.0和MATLAB 2014中都运行了以下代码。时差是愚蠢的,即超过两个数量级。在Windows笔记本电脑上运行可以做些什么来提高Octave的计算速度?
startTime = cputime;
iter = 1; % iter is the current iteration of the loop
itSum = 0; % itSum is the sum of the iterations
stopCrit = sqrt(275); % stopCrit is the stopping criteria for the while loop
while itSum < stopCrit
itSum = itSum + 1/iter;
iter = iter + 1;
if iter > 1e7, break, end
end
iter-1
totTime = cputime - startTime
Octave:totTime~112
MATLAB:totTime&lt; 0.4
答案 0 :(得分:1)
在循环中需要进行大量迭代才能计算代码中的结果。对代码进行矢量化将有助于加快速度。我的下面的代码正是你所做的,但是对计算进行了很多的矢量化。看看它是否有帮助。
startTime = cputime;
iter = 1; % iter is the current iteration of the loop
itSum = 0; % itSum is the sum of the iterations
stopCrit = sqrt(275); % stopCrit is the stopping criteria for the while loop
step=1000;
while(itSum < stopCrit && iter <= 1e7)
itSum=itSum+sum(1./(iter:iter+step));
iter = iter + step+ 1;
end
iter=iter-step-1;
itSum=sum(1./(1:iter));
for i=(iter+1):(iter+step)
itSum=itSum+1/i;
if(itSum+1/i>stopCrit)
iter=i-1;
break;
end
end
totTime = cputime - startTime
使用上面的代码我的运行时间只有0.6秒。如果您不关心循环何时停止,则以下代码更快:
startTime = cputime;
iter = 1; % iter is the current iteration of the loop
itSum = 0; % itSum is the sum of the iterations
stopCrit = sqrt(275); % stopCrit is the stopping criteria for the while loop
step=1000;
while(itSum < stopCrit && iter <= 1e7)
itSum=itSum+sum(1./(iter:iter+step));
iter = iter + step+ 1;
end
iter=iter-step-1;
totTime = cputime - startTime
在后一种情况下,我的运行时间仅为0.35秒。
答案 1 :(得分:0)
您也可以尝试:
itSum = sum(1./(1:exp(stopCrit)));
%start the iteration
iter = exp(stopCrit-((stopCrit-itSum)/abs(stopCrit-itSum))*(stopCrit-itSum));
itSum = sum(1./(1:iter))
使用此方法,您只需要1或2次迭代。但是你当然每次都对整个阵列求和。