I am executing a MatLab program. I used tic-toc to compute execution time. BUT each time I run the code I got a different answer(execution time), Why? and how to compute the execution time in this case?
The tic-toc period will always have a slight variability when re-run. The execution time in this case will be the average of say 10 executions. SUM(t1,t2,...t10)/10.
the execution time of a Matlab task depends on many different factors even for the same task (operating system, scheduling policy of the operating systems, concurrent threads/processes running on machine, etc...)
Even the same task has a execution time different if there are no other threads running or if there are other CPU intensive threads running.
As a metter of fact that in Matlab documentation for tic (below reported the link) it is clearly written
[" ... Value of the internal timer at the execution of the tic command. This value is used as an input argument for a subsequent call to toc. You should not rely on the meaning of this value. ..."]
Anyway, if the machine environment of executing Matlab task is pretty stable, and you should make it so if you want your numbers reproducible, instead of computing an execution time you could compute an average execution time +/- standard deviation.
For instance, the code below makes matrix division of the same 2 matrices 100 times. As you can see from the plot, the executing time is always different but you could have an average execution time +/- standard deviation.
Hello. Since execution time does vary, as pointed out above, due to various factors including processor loading, you could run your program in a loop, say 100 times, and use the Matlab profiler to report on the execution time. You will also get a break-down of the time spent on individual functions, which is very useful for speeding up your code.
I have got explanation from an expert I want to share it with you ...
You computer is a multitasking machine. Sometimes it puts your program on hold to take care of other tasks. The number of other tasks that are going on at any given time can vary both in number and priority so the amount of time it has to pause your program varies. Hence the different times.
I believe that is more or less what the guys above were trying to convey. The issue could be paraphrased in many ways but the core idea is the same; it all boils down to the OS. That answers the first part of your question (Why?).
Now the "How?" question. For the sake of your thesis' submission deadline, if you want to keep it simple just resort to using the average value of multiple runs. Else if you want to thoroughly debug and optimize your code, be it a local function or a specific block of code (e.g., while/for loops), then you could use the profiler as suggested above. Also if you are after a detailed fancy tables/figures rather then mere average value then the profiler is again your answer.