Compute Elapsed Time

TIMER is a directory of MATLAB programs which compute the elapsed CPU time or wallclock time of a part of a calculation.

The idea is that you want to determine the amount of CPU time taken by a piece of your code, so you write lines like this:

        t_start = timer;

        ...some big calculation...

        t_stop = timer;

        fprintf ( 1, 'Elapsed CPU time = %f\n', t_stop - t_start );

MATLAB includes a function CPUTIME, which returns the CPU time in seconds. This represents the amount of computer time "used" by your program, and could be somewhat less than the elapsed wall clock time.

MATLAB includes a function CLOCK which returns the YMDHMS date as a vector of six integers. Two values of CLOCK can be subtracted, and the difference, or elapsed "wall clock time", returned in seconds, by the function ETIME.

MATLAB includes two functions TIC and TOC. If TIC is called before something is to be timed, and TOC is called afterward, then TOC will either print the elapsed wallclock time if its value is not being copied to a variable, or return the value of the elapsed wallclock time to a variable.

To time an entire program, the simplest method to get the elapsed wallclock time is to call tic before you run the program and toc afterwards:

If toc is called without an output argument, it prints the elapsed time. or you can save the output from toc and print it yourself.
        wtime = toc
        fprintf ( 1, '  MY_PROGRAM took %f seconds to run.\n', wtime );

For parallel programming, the important thing to measure is the elapsed wallclock time. This can be found by subtracting an initial reading of the wallclock time from a final one.

The OpenMP system provides a function used as follows:

        seconds = omp_get_wtime ( )
        operations to time;
        seconds = omp_get_wtime ( ) - seconds;
while the MPI system provides a similar function used as:
        seconds = MPI_Wtime ( );
        seconds = MPI_Wtime ( ) - seconds;
and in MATLAB, wallclock time can be taken with "tic" and "toc":
        seconds = toc;


The computer code and data files described and made available on this web page are distributed under the GNU LGPL license.


TIMER is available in a C version and a C++ version and a FORTRAN77 version and a FORTRAN90 version and a MATLAB version and a PYTHON version.

Related Data and Programs:

TIC_TOC, MATLAB programs which demonstrate some features of MATLAB's tic and toc functions for wallclock timing.

TIMESTAMP, a MATLAB library which prints out the current YMDHMS date.

WTIME, a MATLAB library which returns a reading of the wall clock time in seconds.

Examples and Tests:

CPUTIME_TEST uses the CPUTIME routine:

ETIME_TEST uses the ETIME routine:

TICTOC_TEST uses the TIC and TOC routine:

There are a few auxilliary routines you may need:

You can go up one level to the MATLAB source codes.

Last revised on 16 June 2006.