timing code in matlab
The best way to time MATLAB code is to use timeit, available from the MATLAB Central File Exchange.
It was implemented by Steve Eddins, one of the senior developers at MathWorks, and it takes care of a lot of subtleties in timing your code. For example, code runs very differently when it's executed within a function rather than within a script, and it needs to have a couple of "warm-up" runs in order to take proper advantage of the JIT compiler. It will also run the code many times in a loop, and take the median.
These things are difficult to get right without knowing a fair amount about how MATLAB works under the hood, and timeit
takes care of these things for you - simple applications of tic
and toc
do not.
Using the profiler, as other answers have suggested, is problematic as it switches off many aspects of the JIT compiler, and will not run at the same speed as it does normally. Profiler does a great job of telling you which portions of your code take a relatively large proportion of time, i.e. discovering bottlenecks, but it's not intended for giving you actually realistic timings.
Note that in the most recent version (R2013b), timeit
is available as part of core MATLAB, and does not need to be obtained from the File Exchange.
For example, to time your function one
with the input argument x
equal to 64, you would type:
myfun = @()one(64);
timeit(myfun);
What this does is to make a function handle to your function one
(which makes sure that the code is executed inside a function, important as mentioned above), then passes this function handle into timeit
. The output is timeit
's estimate of the time taken to execute the code.
The profiler is one possibility, but it will slow down your code significantly.
Alternatively you could store the toc
value within your loop or after every function call.
t(i) = toc
and then compare these values, compute the mean or whatever, like you would deal with other vectors.