Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: 30% faster for-loop when changing loop variable from default(double) to int
Date: Mon, 14 May 2012 15:31:07 +0000 (UTC)
Organization: Institute of Physics, Academia Sinica,Taiwan
Lines: 43
Message-ID: <jor8fr$a4n$1@newscl01ah.mathworks.com>
Reply-To: <HIDDEN>
NNTP-Posting-Host: www-00-blr.mathworks.com
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 8bit
X-Trace: newscl01ah.mathworks.com 1337009467 10391 172.30.248.45 (14 May 2012 15:31:07 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Mon, 14 May 2012 15:31:07 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 1196600
Xref: news.mathworks.com comp.soft-sys.matlab:767776

When testing a very simple program and trying to change the for-loop variable from double to int (Why did I do that?), I found the program becomes faster, about 30%.
The program is as following:

function k=pbug_d(N)
    p=0.3;
    
    for i=1:N
        p=3.4*(p*(1-p));
    end 

k=p;
end

On my PC (Pentium 6700, Win7, MatlabR2010b),  the command

tic, pbug_d(1e9),toc

took 9.3s.

When I changed the for-loop variable to int type:

 function k=pbug_i(N)
    
    p=0.3;
    
    i=int32(1);
    
    for i=1:N
        p=3.4*(p*(1-p));
    end 
    k=p;
end

the command

tic, pbug_i(int32(1e9)),toc  %the input type should also be int

gave the same result(ans= 0.451963247626153) 
and took only 6.6s, ~30% faster!

This result sounds good. A simple data type change brings 30% better performance.
I also tested them under Linux (Ubuntu 12.04, LTS, MatlabR2010b) and got the similar result. 
While when I compiled the .m file into mex file, there is little difference for int and double for-loop variable. In linux, the compiled mex using int loop variable even becomes a little slower than double type. Anyone knows why?