MATLAB: Does a function execute much slower than other similar functions

averageMATLABoptimizationperformancetictimingtoc

I am timing "sum", "mean", and vectorized forms of those functions using the following script:
 
n = 1000000;
vec1 = ones(1,n);
x = randn(n,1);
disp('Vectorized sum')
tic
Sum = vec1*x;
toc
disp('Matlab function sum')
tic
Sum_matlab = sum(x);
toc
disp('Vectorized mean')
tic
Mean = vec1*x/n;
toc
disp('Matlab function mean')
tic
Mean_matlab = mean(x);
toc
I receive the following output:
 
Vectorized sum
Elapsed time is 0.000846 seconds.
Matlab function sum
Elapsed time is 0.000413 seconds.
Vectorized mean
Elapsed time is 0.000602 seconds.
Matlab function mean
Elapsed time is 0.010935 seconds.
Why does "mean" take so much longer to run?

Best Answer

The individual execution times of a function can fluctuate widely depending on what else may be running on the computer. For example, if you run the previous script multiple times, you will likely notice that the values change each time, sometimes dramatically. One way to more accurately judge the execution time of a function is to run it repeatedly and calculate the average of the execution times. For example, consider the following script:
 
numberOfRuns = 1000; % Each operation will be executed and timed this many times
averages = [0,0,0,0]; % Holds averages for each calculation
n = 1000000;
vec1 = ones(1,n);
for i = 1:numberOfRuns
x = randn(n,1);
% Vectorized sum
tic
Sum = vec1*x;
averages(1) = averages(1) + toc;
% Matlab function sum
tic
Sum_matlab = sum(x);
averages(2) = averages(2) + toc;
% Vectorized mean
tic
Mean = vec1*x/n;
averages(3) = averages(3) + toc;
% Matlab function mean
tic
Mean_matlab = mean(x);
averages(4) = averages(4) + toc;
end
averages = averages ./ numberOfRuns; % Take average
disp('Vectorized sum:')
disp([' ' num2str(averages(1)) ' seconds average'])
disp('Matlab function sum:')
disp([' ' num2str(averages(2)) ' seconds average'])
disp('Vectorized mean:')
disp([' ' num2str(averages(3)) ' seconds average'])
disp('Matlab function mean:')
disp([' ' num2str(averages(4)) ' seconds average'])
When I executed this, I receive the following output:
 
Vectorized sum:
0.00064485 seconds average
Matlab function sum:
0.00040692 seconds average
Vectorized mean:
0.00040477 seconds average
Matlab function mean:
0.00042016 seconds average
It appears that the built-in "mean" function may take slightly longer to execute than "sum", but it is not as dramatic an increase as was seen by timing each function once.