MATLAB: Significant differences in execution time

MATLABtictimingtoc

I'd like to measure the execution time of two different operations. I see significant differences when executing a script or executing the same commands in the command window.
Command Window:
>> clear all
>> n = 1e7; x = randn(n,1);
>> tic, s = 0; for i=1:n, s = s + x(i)^2; end, toc
Elapsed time is 0.396205 seconds.
>> tic, s = sum(x.^2); toc
Elapsed time is 0.031208 seconds.
Script (timings.m):
clear all
n = 1e7; x = randn(n,1);
tic, s = 0; for i=1:n, s = s + x(i)^2; end, toc
tic, s = sum(x.^2); toc
Calling the script results in:
>> timings
Elapsed time is 7.230688 seconds.
Elapsed time is 0.085515 seconds.
So the for loop is about 20 times slower compared to the command window execution!
Script (timings2.m):
clear all
n = 1e7; x = randn(n,1);
tic, s = 0; for i=1:n, s = s + x(i)^2; end, toc
clear all
n = 1e7; x = randn(n,1);
tic, s = sum(x.^2); toc
Calling the script results in:
>> timings2
Elapsed time is 0.036559 seconds.
Elapsed time is 0.036499 seconds.
Now the for loop is about 10 times faster compared to the command window execution!
What is the reason for these differences in execution time? How should one measure the execution time of the the different statements?

Best Answer

Hi,
in addition to Sara's comment take a look at the function timeit, that was introduced in R2013b (if you are using an older version, take a look at this file on the fileexchange.
Titus