2016-03-22 18 views
1

Aşağıdaki kodu hem Octave 4.0.0 hem de MATLAB 2014'te çalıştırdınız. Zaman farkı saçma, yani ikiden fazla büyüklük sırası. Windows dizüstü bilgisayarda çalışıyor. Octave hesaplama hızını geliştirmek için neler yapılabilir?oktav yavaştır; öneri

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 < 0.4

+0

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

cevap

1

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

+0

Biraz kafa karıştırıcı çünkü kodunuz adım adım adım adım '1 + 1' – Daniel

+0

@Daniel, siz haklısınız.Kodumun amacı sadece kodun vektörel hale getirildiğini göstermek için biraz hızlandırabilmekti.Ayrıca adım = 1001, orada Ayrıca, adımı ayarlama gibi kodumu geliştirmenin bir başka yolu da, ilk döngüden sonra "itSum

0

: Bu Methode ile

itSum = sum(1./(1:exp(stopCrit))); 
    %start the iteration 
    iter = exp(stopCrit-((stopCrit-itSum)/abs(stopCrit-itSum))*(stopCrit-itSum)); 
    itSum = sum(1./(1:iter)) 

Eğer sadece 1 veya 2 iterasyon sahip olacaktır. Ama elbette, tüm diziyi her seferinde toplamış olursunuz.