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 CenterFile Exchange에서 Arithmetic Operations에 대해 자세히 알아보기

태그

제품


릴리스

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by