Why does the execution time of the same MATLAB code changes when I run it 2-3 times?

37 views (last 30 days)
In my application, it is necessary to know the execution time for particular section of the code. I use tic; & toc; inbuilt option to know the execution time of the section of code but when i run the same code with same variables 2 to 3 times, it shows different execution time. why is that? & can anyone explain how to get the exact execution time for a section of code?

Accepted Answer

James Tursa
James Tursa on 27 Jun 2014
First, there is no such thing as "the exact execution time" of a piece of code in the sense you are talking about. Tic-toc returns the time it took for a particular execution. Running it multiple times can naturally produce different timing results because of things like: Different processes running in the background that you have no control over, Caching of memory has changed between runs, MATLAB JIT may have done more code optimization between runs, etc. Particularly for short sections of code it can be difficult to get timings that don't vary. The best you will typically be able to achieve is an "average" run-time of sorts by doing multiple runs. And probably throw out the first run to eliminate the effect of first-time loading and parsing of the code involved.
  4 Comments
Kevin Sanghvi
Kevin Sanghvi on 1 Jul 2014
I understand. the code involves matrix multiplication & for loop that's it. but even if i run this below code:
tic; for i=1:1000 end toc;
the execution time is different for multiple runs...
James Tursa
James Tursa on 1 Jul 2014
The loop you show has very little computation going on, so the run time will be dominated by other things and can vary widely in a relative sense. Timings are not meaningful in this case.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!