Optimise code and identify bottlenecks - hints and tips
7 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Morning all,
I have just got a brand spanking new computer that is supposed to kick my old one in the butt for speed. It doesn't!
Do you have any general tips for speeding up code? For example pre-allocating memory etc.
Many thanks
0 Commenti
Risposte (1)
Marc Jakobi
il 7 Ott 2016
Modificato: Marc Jakobi
il 7 Ott 2016
mathworks.com/company/newsletters/articles/programming-patterns-maximizing-code-performance-by-optimizing-memory-access.html
and
mathworks.com/company/newsletters/articles/accelerating-matlab-algorithms-and-applications.html
2 Commenti
Marc Jakobi
il 7 Ott 2016
Yes, I think it is because of the optimization algorithm. The Fortran code behind Matlab doesn't have to loop over columns or something like that. Or it has something to do with indexing. I'm not sure.
There are lots of little things you learn over time. One thing I like to do is pre-allocate memory for a variable who's size I don't know of beforehand.
So for example, most people would use
x = [];
for i = 1:length(y)
if y(i) > 0
x = [x; x];
end
end
But it can often be faster to pre-allocate x with its maximum possible size and shorten it later:
x = zeros(size(y));
ct = 0;
for i = 1:length(y)
if y(i) > 0
ct = ct + 1;
x(ct) = y(i);
end
end
x = x(1:ct);
The most important thing in my opinion is to use doubles only when necessary. It's much easier when coding to declare everything as a double (the default), but if you always declare them as the smallest possible data types you need it to be and casting when necessary, it's tedious at first, because you have to keep looking up what the limits are, but you get used to it.
Vedere anche
Categorie
Scopri di più su Web Services in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!