O Kodunuzdaki sonuçları hesaplamak için döngü içinde tekrarlamalar çok zaman alır. Kodun vektör edilmesi çok hızlanmaya yardımcı olacaktır. Aşağıdaki kod, yaptığınız şeyi tam olarak yapıyor, ancak hesaplamayı birazcık hale getirin. Yardım edip etmediğine bakın.
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
Yukarıdaki kod kullanılarak çalışma zamanım yaklaşık 0,6 saniyedir. Eğer döngü durur tam olarak ne zaman umurumda değil, aşağıdaki kod daha hızlı geçerli:
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
Benim çalışma zamanı ikinci durumda sadece yaklaşık 0.35 saniyedir. Ayrıca deneyebilirsiniz
Fonksiyonunuzun harmonik seri toplamını hesapladığını farkettim. Bu nedenle, çok fazla yinelemeye sahipseniz, örneğin toplamı (1/1 (exp: stopCrit)) kullanmak daha iyidir ve sonra toplamı (1 ./ (1: #iteration)) = stopCrit değerine kadar ayarlayın. – obchardon