matlabfunctiontimecpu-time

MATLAB Cpu time =0 issue


I have written a function in MATLAB. Within that function I use:

t = cputime;
...
time = cputime-t;

Where I have some operations at the dots. Whenever I don't call the function and instead run the code in the function manually, I always have time = 0.15 etc.

However, in another script, I am calling this same function. In the first call, it is again giving me time = 0.15. BUT, if I clear the workspace and call the function again, I have time = 0. Just 0, no decimals. I don't know why, because the function is working and giving me what I want. If I instead run the code in the function many times, I never have time = 0.

What is the possible issue? Why calling a function from the script more than once makes it 0 seconds even if the workspace is cleared?


Solution

  • You should always use the function timeit to time code. Anything else is inaccurate at best.

    timeit first “warms up” the system, then runs the code repeatedly to obtain a precise estimate of the time it takes.

    Using cputime or tic/toc leads to imprecise measurements when the code to be executed is short. The resolution of the clock is just not fine enough to properly measure it (which is why you can see 0 instead of a very small number), and the measurement can be affected by other stuff going on in your computer at the same time.

    Lastly, MATLAB uses a JIT (Just In Time) compiler. Code inside a function is parsed and compiled once the first time you execute it. Subsequent times simply reuse the compiled code, so run much faster.

    In this regard, the difference between a function and a script M-file is not clear to me. It used to be the case that scripts were not JIT-compiled, only functions were. But I suspect this might have changed in recent versions of MATLAB. In any case, things directly typed or copy/pasted to the command prompt are not JIT-compiled, and therefore will always be as slow as when you run a function for the first time.

    When you do clear all, you clear pre-loaded and pre-compiled code from memory, making subsequent code run slower. You should generally not use clear all. To clear variables just do clear.