Reputation: 295
I am writing some codes in which the calculation time is important. I use tic toc
function and profiler
to measure the time. what is the difference between them?
for a piece of my code, tic toc
function states that for example the time is 3 sec but the sum of times in profiler
for all lines of my code is not that much!
Upvotes: 2
Views: 1140
Reputation: 24137
The profiler is great for finding bottlenecks in your code, and for comparing relative timings for different algorithms, but I wouldn't trust it to give you accurate absolute timings.
For one thing, using the profiler disables many JIT optimisations, so the code may well not run in the same way as it does normally.
Taking timings with tic
and toc
can be quite subtle, as you need to warm up the code and run it a few times to take an average.
I would recommend you use timeit
instead, which handles all of these subtleties for you. In recent versions timeit
is part of core MATLAB. If you're using an older version, you can download it from the MATLAB Central File Exchange.
Upvotes: 4
Reputation: 735
TIC TOC
and profiler
do very different things.
TIC TOC measures the elapsed time from the call of TIC to the call of TOC. This includes some overhead within the tic functions themselves and for very sorry intervals, is not totally reliable.
Profiler measures the cpu time for the execution of each function within your code. This does not include downtime during which no function is currently executed (the cpu is performing other tasks, including running your matlab code).
There are other things you should do to ensure a precise calculation of time:
Wrap the code in a function to ensure it is JIT compiled.
Warm up the function by running it once prior to profiling.
Run the code multiple times and average the times.
Run the tic/toc function many times, average the result, and subtract that from your total time.
If possible, allocate arrays outside of any loops, rather than appending to an array.
Upvotes: 2