Which of these two assignments is more efficient
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Please have a look at the function below and let me know which of the sections labelled (1) and (2) is more efficient.
function pw =realtime_func(c)
persistent c_mem;
if isempty(c_mem)
c_mem=zeros(30,1);
end
%%(1) Is this faster
c_mem=[c_mem(2:end);c];
%%(2) or is this faster
c_mem(1)=[];
c_mem(end+1)=c;
% output
pw=hasTrumpCrashedTheEconomyYet(c_mem);
end
1 commentaire
KSSV
le 15 Nov 2016
You can run a profiler to check your self or you can use tic, toc to check the timings. By the way is your label (2) working? It will throw error.
Give details, what is c and what you want to do.
Réponse acceptée
Jan
le 15 Nov 2016
Most likely method 1 is faster, because 2 must allocate 2 arrays. But Matlab's JIT acceleration might recognize this and optimize the code. So the only reliable answer is to measure it. Use timeit or run a tic toc and a loop with perhaps 1 million iterations.
Note that asking in the forum needs some time also. So you will have to run the faster version trillions of times to get the invested time back. Is this piece of code really the bottleneck of the complete program? If not: Avoid "premature optimization" (search this term in the net in case of doubts).
Plus de réponses (1)
James Tursa
le 15 Nov 2016
Modifié(e) : James Tursa
le 15 Nov 2016
Another method to try that might be faster for your application:
%%(3) or is this faster
c_mem(1:end-1)=c_mem(2:end);
c_mem(end)=c;
2 commentaires
Jan
le 16 Nov 2016
It seems like [c_mem(2:end);c] creates the vector c_mem(2:end) explicitely and a new vector, when the last element is added. James solution moves the values inside the existing array whithout allocating a new one.
Voir également
Catégories
En savoir plus sur Target Computer Setup dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!