Very slow function, excessive overhead?

7 ビュー (過去 30 日間)
Jesse
Jesse 2023 年 3 月 27 日
コメント済み: Walter Roberson 2023 年 3 月 28 日
I've got a function that looks at a n x 2 array (1st column time vector, 2nd column flag vector) and it's running incredibly slow. As you can see, line 17 takes almost all of the runtime. I've read that this could be related to overhead, but I don't actually know what that means or how to improve it. Any ideas on what could be causing this?

採用された回答

Walter Roberson
Walter Roberson 2023 年 3 月 27 日
You are not assigning to flag within your loop, so you should use
flagrows = size(flag,1);
while i < flagrows
end
The end for a loop does get "charged" the cost of the loop overhead, which in this case is doing more computations than required.
  2 件のコメント
Jesse
Jesse 2023 年 3 月 27 日
Thank you! That did the trick. I didn't realize how computationally heavy the "size" function could be. It makes sense though, when you call it nearly 400 thousand times.
Walter Roberson
Walter Roberson 2023 年 3 月 28 日
you used length(flag(:, 1)) which starts by extracting the first column and then taking the length of the column. That sequence involves copying data and then checking the size. That is a lot more work then just checking the size of the original data.

サインインしてコメントする。

その他の回答 (1 件)

Torsten
Torsten 2023 年 3 月 27 日
編集済み: Torsten 2023 年 3 月 27 日
The inner while loop is not necessary: if flag(i,2)-flag(i-1,2) == 1, then of course flag(i,2)-flag(i-1,2) ~== -1. Thus the incrementation i = i+1 will always happen. This is strange since you increment i again after you quit the if-clause.
Preallocating "events" as zeros(size(flag,1),3) and finally cutting it by events = events(1:j-1,:) might speed up the function also.
  1 件のコメント
Jesse
Jesse 2023 年 3 月 27 日
I'm trying to find the start and end point of each flag "event". the outer loop finds when flag goes from 0 to 1, and the inner loop finds whent the flag goes from 1 to 0.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by