Why does the execution time of the same MATLAB code changes when I run it 2-3 times?
37 views (last 30 days)
Show older comments
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?
0 Comments
Accepted Answer
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
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.
More Answers (0)
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!