Optimise code and identify bottlenecks - hints and tips
6 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Respuestas (1)
Marc Jakobi
el 7 de Oct. de 2016
Editada: Marc Jakobi
el 7 de Oct. de 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 comentarios
Marc Jakobi
el 7 de Oct. de 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.
Ver también
Categorías
Más información sobre Web Services en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!