Reputation: 9718
I might have misunderstood something.. but I expected the running of a code in the editor and in the command window to be the same..
I have the following code in the editor
display(' ');
display('script');
fac = @(n) prod(1:n);
n=20;
display(['- use of anonymous function: fac = @(n) prod(1:n); with n = ' num2str(n)]);
tic; fac(n); toc;
display(['- use of build in MatLab function: factorial(); with n = ' num2str(n)]);
tic; factorial(n); toc;
before I run (is that called compiled or execute?) I quickly type in the same command in the command window. Which gives me this:
So all of a sudden the factorial function in the editor got a boost when it comes to performance.. What just happened?
Upvotes: 2
Views: 433
Reputation: 10967
First, the calculation you are trying to measure is too quick to get anything like an accurate reading. It is way below the measurement noise you get when using tic/toc because of other processes and activity on the system. To get more accurate measures repeat the calculation many times... (I would repeat the calculation so it takes 10-20 seconds).
Second, there is indeed a difference between code typed interactively and in a script. I think the JIT only runs for code run from a script or function m-file, where and not for stuff running in the interpreter (but I am struggling to find a reference for this now - I will add if I find it).
Upvotes: 2
Reputation: 11168
you mean the differences in running time between running in command window and running from script? I think they're caused by everything else also running on your computer, matlab's own memory management and a few other things...
it is explained in greater detail here: http://www.mathworks.com/matlabcentral/newsreader/view_thread/296850
Another method of measuring the time spent on cpu is the function cputime. It has however lower precision. So expand your test case in that it takes a longer time (n=2e7 eg factorial is capped at 171) to see results with cputime.
Conclusion: one swallow does not a summer make
Extend your testing with more cases.
n=200;
tic;
for ii=1:1e4
factorial(n);
end;
toc
Upvotes: 1