Main Content

toc

Read elapsed time from stopwatch

Description

example

toc reads the elapsed time since the stopwatch timer started by the call to the tic function. MATLAB® reads the internal time at the execution of the toc function and displays the elapsed time since the most recent call to the tic function without an output. The elapsed time is expressed in seconds.

toc(timerVal) displays the elapsed time since the call to the tic function corresponding to timerVal.

example

elapsedTime = toc returns the elapsed time since the most recent call to the tic function.

example

elapsedTime = toc(timerVal) returns the elapsed time since the call to the tic function corresponding to timerVal.

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.743248 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 1.436023 seconds.
C = A.*B;
toc
Elapsed time is 1.634381 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.5585
tEnd = toc(tStart)      % pair 2: toc
tEnd = 14.8667

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.

Input Arguments

collapse all

Value of the internal timer saved from a previous call to the tic function, specified as a scalar of type uint64.

Tips

  • Consecutive calls to the toc function with no input return the elapsed time since the most recent call to tic. This property enables you to take multiple measurements from a single point in time.

    Consecutive calls to the toc function with the same timerVal input return the elapsed time since the tic function call that corresponds to timerVal.

  • 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