Calculate & Compare the execution time of various Functions & Modules in MATLAB

MATLAB does provide us with the facility to calculate the execution time of a particular function. Just in case if someone wants to optimize his/her code so as to take the minimum execution time, it would be very necessary part.

The keywords for it MATLAB are, tic & toc.
When ever we want to calculate execution time of our code snippet, we put those lines of code inside tic-toc.

For Example: 
Given that variable a & b are predefined.
tic
c=a*`b;
% to suppress the output echo of c
toc

So the above code will result MATLAB to echo like this : Elapsed time is 0.003059 seconds.

Also the execution time in MATLAB you will not get same all time, even of the same function & code lines!

As when above code is repeated many more times, the result are echoed as:
>> tic
c=a*b';
toc
Elapsed time is 0.002946 seconds.

>>  tic
c=a*b';
toc
Elapsed time is 0.003181 seconds.

>>  tic
c=a*b';
toc
Elapsed time is 0.002386 seconds.

>>  tic
c=a*b';
toc
Elapsed time is 0.002341 seconds.

Thus if optimization of the code is your primary objective, taking the average of the above elapsed time is recommended for multiple attempts, so as to get an idea for a larger picture.

Comparing execution time of functions & code snippets:

Suppose: a=[1 2 3 4] & b=[5 2 1 4] 

Then we want to calculate & compare the execution time for the operations a*b' & a.*b (equivalent to times(a,b)), which is Matrix multiplication & array multiplication. So we just need to put them under the tic-toc block. The result will be like:

tic
d=a.*b
toc

d =

     5     4     3    16

Elapsed time is 0.002758 seconds.

tic
c=a*b'
toc

c =

    28

Elapsed time is 0.003166 seconds.


For the above result its obvious that operation c=a*b' require more addition & multiplication steps as compared to d=a.*b so the execution time is more. 

But there are cases, that we have two paths for calculating the same output but through different methods. Standard example of which, is calculation of n! (Factorial), with & without recursion, obviously the former will execute faster than the latter one.

Further Reading: A Guide to optimize MATLAB code


0 comments: