フィルターのクリア

Optimise code and identify bottlenecks - hints and tips

9 ビュー (過去 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 Center および File ExchangeMATLAB についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by