extremely inefficient piece of code ... bug?

3 ビュー (過去 30 日間)
Michal
Michal 2023 年 8 月 31 日
編集済み: Matt J 2023 年 8 月 31 日
I have two codes that implement exactly the same task:
idx(idx<=0) = 1;
idx(idx>=n) = n-1;
and
if idx <= 0
idx = 1;
elseif idx >= n
idx = n-1;
end
where idx and n are a scalar integer values.
This piece of code is evaluating multiple times (N = 1e6, for example). During profiling of the code, I found very strange inefficiency of the first code, which is about ~ 100-1000x slower than the 2nd one. I use the 1st type of code to get more readable code by avoiding if-else construct, but the overall performance is on R2023a really terrible. See attached test code (test.m).
Is this behavior normal, or is it a BUG?
Please, could you verify this code on other (older) MATLAB releases to see, if the problem is only R2023a related or not?
  24 件のコメント
Bruno Luong
Bruno Luong 2023 年 8 月 31 日
Cheese: For the record: My timing figure is directed to Rik's comment, then you continue to draw me in with your justification about your montecarlo simulation, that I initially never ask for. I'm not really interested in knowing the topic to be honest. That's your work not mine. You don't need to attck me with "Especially if you don't know anything about the topic at hand."
Michal
Michal 2023 年 8 月 31 日
編集済み: Michal 2023 年 8 月 31 日
@Bruno Luong I just react on your statement: "Don't tell me that you mainly do scalar clipping on your montecarlo simulation."
I tried to explain to you why I use "scalar clipping" in my MC simulation. You finally comment my explanation by: "Noise interpolation has no sense to start with...."
So, what ...?

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

採用された回答

Matt J
Matt J 2023 年 8 月 31 日
編集済み: Matt J 2023 年 8 月 31 日
Well, I think the bottom line is just that the JIT does not have any optimization for indexing expressions like idx(idx<=0). That might be because such an optimization would need to know in advance that idx is a scalar, and remains a scalar throughout the loop.
Coversely, parsing an if-statement,
if idx>threshold
end
doesn't require nearly as much work, even when idx is a vector. The if test is done by looping through the vector elements idx(i)>threshold, and as soon as one of the elements is false, it bails out.
  5 件のコメント
Michal
Michal 2023 年 8 月 31 日
This is only a special (scalar) case of general array logical indexing... Why should be this special case penalized by absence of optimization?
Matt J
Matt J 2023 年 8 月 31 日
編集済み: Matt J 2023 年 8 月 31 日
No, I'm saying that to achieve the same performance you're seeing with if-else, the scalar indexing case would have to receive its own special treatment from the JIT, separate from what is normally done for general logical indexing.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeArithmetic Operations についてさらに検索

タグ

製品


リリース

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by