Optimise code and identify bottlenecks - hints and tips
6 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
Marc Jakobi
2016-10-7
编辑:Marc Jakobi
2016-10-7
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 个评论
Marc Jakobi
2016-10-7
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Web Services 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!