Here are three ways to use tic/toc to measure the timing of a loop. Each method has pros and cons.
Method 1: Least overhead & resolution
The tic() & toc() functions require processing time, albeit a very small amount. Storing the results of toc() also requires processing time. This method contains the least overhead but you don't get the single-iteration times.
Method 2: Single iterations times
This method gives you the single-iteration times but the processing time is added by tic/toc and storing the toc output.
Method 3: Single iterations times, less overhead
This method removes tic() from the loop which doesn't reduce the overhead by much but it's worth sharing. The single-iteration times are computed outside of the loop.
Reasons your timing was off
- tic() returns an integer (uint64) that has meaning only for the toc function. Example: t = tic(); t = 1943576784277
- toc() returns the elapsed time since the previous tic() which is very quick in your loop so you're subracting a tiny amount from a large, meaningless integer.
- The 1+1 and 2+2 lines display the result of each iteration in the command window since those lines are not supressed with a semicolon (;). That takes a lot of time.
- The t variable was not pre-allocated so the length of t grows with each iteration. That also takes a lot of time.
Since the computations are so simple, you'll find a wide range of mean(t) if you run that script many times. Consider using the timeit function.
Best Answer