Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: if statements - drastic difference in running time
Date: Thu, 22 Mar 2012 14:43:12 +0000 (UTC)
Organization: Dalhousie University
Lines: 33
Message-ID: <jkfdq0$ouv$1@newscl01ah.mathworks.com>
References: <jkf6uj$ni$1@newscl01ah.mathworks.com>
Reply-To: <HIDDEN>
NNTP-Posting-Host: www-04-blr.mathworks.com
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 8bit
X-Trace: newscl01ah.mathworks.com 1332427392 25567 172.30.248.35 (22 Mar 2012 14:43:12 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Thu, 22 Mar 2012 14:43:12 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 3353142
Xref: news.mathworks.com comp.soft-sys.matlab:761844

"MaxEOE" wrote in message <jkf6uj$ni$1@newscl01ah.mathworks.com>...
> Hi,
> I have encountered the following odd behavior I have no explanation for:
> In the following code snippet I observe dramatically different running times, depending on the usage of the if statements, which both give the same results. The if query 2 takes about ten times longer than the if query 2.
> Has anyone an explanation for this? I run the code on Matlab 7.8.0.347 (R2009a).
> 
> tic;
> 
> r_array = rand(10,1);
> for i=1:10
>     r1 = r_array(i);
>     r2 = rand(1);
>     T = 0;
>     for j=1:1000000
>         T = T + 0.000001;
>          if r1<T        % if query 1
> %      if r2<T        % if  query 2
>              display(i);
>              break
>          end
>     end
> end
> 
> toc;
> 
> Thank you,
> MaxEOE

I'm stuck guessing here. But I assume you mean to say that it is ~10 times longer to use if #1 than if #2. If you were a super-smart MATHWORKS guy, and you were designing an interpreted language, it might be nice if you could notice when the same statement is getting evaluated over and over again. When that happened, you could just cache the result and keep re-applying it, without having to (expensively!) re-evaluate the same statement.

Now. look at your second "if" statement. I could cache the result once, and then use it all 10*1000000 times in your set of nested loops. But for "if" statement #2, I'd have to re-compute that value every time the value of r1 changed. That happens - you guessed it - ten times. This is why your first script takes ten times longer to execute than the second - the if statement is computed ten times, instead of one time*.

*(I'm lying a bit here, but that gives the gist. I'd love to see someone give a more detailed explanation as to *how* MATLAB caches these results, and *how* it recognizes when a statement needs to be re-evaluated.)