user3482383
user3482383

Reputation: 295

TIC TOC or Profiler

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

Answers (2)

Sam Roberts
Sam Roberts

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

Juderb
Juderb

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:

  1. Wrap the code in a function to ensure it is JIT compiled.

  2. Warm up the function by running it once prior to profiling.

  3. Run the code multiple times and average the times.

  4. Run the tic/toc function many times, average the result, and subtract that from your total time.

  5. If possible, allocate arrays outside of any loops, rather than appending to an array.

Upvotes: 2

Related Questions