Skip to main content

Section 4.5 Measuring the computation time

Since loops may run for a long time, it is worthwhile to compare the time required by different approaches. To do this, we can use the combination of tic and toc commands: insert tic at the beginning of the code that should be timed, and toc at the end. The time elapsed between tic and toc will be shown in the Matlab command window.

Let us compare two ways of computing the sum of cosines of all integers from \(1\) to \(10^7\text{:}\) a loop and an array operation. Which one is faster?

n = 1e7;
tic
s = 0;
for j = 1:n
    s = s + cos(j);
end
toc
disp(s)

tic
s = sum(cos(1:n));
toc
disp(s)

An array operation is not always faster than a loop. Operating with large arrays requires more memory to store intermediate results. Other internal implementation details may cause a loop with a scalar operation to be faster than an array operation. Thus, we usually cannot tell which approach is faster without measuring the computation time. For more examples, try different ways of computing the sums \(\sum_{j=1}^n \frac{1}{j}\) and \(\sum_{j=1}^n j^3\) where \(n=10^7\) as before. Also note that \(j^3\) could be computed as j*j*j: does this speed up the computation?