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;
averages = [0,0,0,0];
n = 1000000;
vec1 = ones(1,n);
for i = 1:numberOfRuns
x = randn(n,1);
tic
Sum = vec1*x;
averages(1) = averages(1) + toc;
tic
Sum_matlab = sum(x);
averages(2) = averages(2) + toc;
tic
Mean = vec1*x/n;
averages(3) = averages(3) + toc;
tic
Mean_matlab = mean(x);
averages(4) = averages(4) + toc;
end
averages = averages ./ numberOfRuns;
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.
Best Answer