Optimise code and identify bottlenecks - hints and tips

조회 수: 6 (최근 30일)
jlt199
jlt199 2016년 10월 7일
댓글: Marc Jakobi 2016년 10월 7일
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

답변 (1개)

Marc Jakobi
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
jlt199
jlt199 2016년 10월 7일
Excellent, I didn't know storing data in columns was quicker than doing the same with rows.
Any other useful tidbits?
Marc Jakobi
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 CenterFile Exchange에서 Web Services에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by