Main Content

tic

Start stopwatch timer

Description

tic works with the toc function to measure elapsed time. The tic function records the current time, and the toc function uses the recorded value to calculate the elapsed time.

example

timerVal = tic stores the current time in timerVal so that you can pass it explicitly to the toc function. Passing this value is useful when there are multiple calls to tic to time different parts of the same code. timerVal is an integer that has meaning only for the toc function.

example

Examples

collapse all

Measure the time required to create two random matrices.

tic
A = rand(12000,4400);
B = rand(12000,4400);
toc
Elapsed time is 0.814688 seconds.

Measure the elapsed time since a call to the tic function at different points of the program.

tic
A = rand(12000,4400);
B = rand(12000,4400);
toc
Elapsed time is 0.777485 seconds.
C = A.*B;
toc
Elapsed time is 0.855424 seconds.

Use a pair of tic and toc calls to report the total time required for element-by-element matrix multiplication; use another pair to report the total runtime of your program.

tStart = tic;           % pair 2: tic
n = 10;
T = zeros(1,n);
for i = 1:n
    A = rand(12000,4400);
    B = rand(12000,4400);
    tic         % pair 1: tic
    C = A.*B;
    T(i)= toc;  % pair 1: toc
end
tMul = sum(T)
tMul = 
0.3255
tEnd = toc(tStart)      % pair 2: toc
tEnd = 
8.1729

The variable tMul includes the total time spent on multiplication. tEnd specifies the elapsed time since the call to the tic function at the beginning of the program.

Tips

  • Consecutive calls to the tic function overwrite the internally recorded starting time.

  • The clear function does not reset the starting time recorded by a tic function call.

  • Sometimes programs run too fast for tic and toc to provide useful data. If your code is faster than 1/10 second, consider measuring it running in a loop, and then average to find the time for a single run. For more information, see Measure the Performance of Your Code.

  • The following actions result in unexpected output:

    • Using tic and toc to time timeit
    • Using tic and toc within a function timed by timeit

Extended Capabilities

Version History

Introduced before R2006a