Documentation

timeit

Measure time required to run function

Syntax

t = timeit(f)
t = timeit(f,numOutputs)

Description

example

t = timeit(f)measures the typical time (in seconds) required to run the function specified by the function handlef.

example

t = timeit(f,numOutputs)callsfwith the desired number of outputs,numOutputs. By default,timeitcalls the functionfwith one output (or no outputs, if the function does not return any outputs).

Examples

collapse all

Usetimeitto time a function call todate. This example uses a handle to a function that accepts no input.

f = @date; t = timeit(f)
t = 1.1792e-04

Time the combination of several mathematical matrix operations: matrix transposition, element-by-element multiplication, and summation of columns.

A = rand(12000,400); B = rand(400,12000); f = @() sum(A.'.*B, 1); timeit(f)
ans = 0.0718

Determine how long it takes to runsvdwith one output argument,s = svd(X).

X = rand(100); f = @() svd(X); t1 = timeit(f)
t1 = 0.0108

Compare the results tosvdwith three output arguments,[U,S,V] = svd(X).

t2 = timeit(f,3)
t2 = 0.0167

Create a short function to allocate a matrix using nested loops. Preallocating an array using a nested loop is inefficient, but is shown here for illustrative purposes.

functionmArr = preAllocFcn(x,y)form = 1:xforn = 1:y mArr(m,n) = 0;endendend

Compare the time to allocate zeros to a matrix using nested loops and using thezerosfunction.

x = 1000; y = 500; g = @() preAllocFcn(x,y); h = @() zeros(x,y); diffRunTime = timeit(g)-timeit(h)
diffRunTime = 0.1584

Input Arguments

collapse all

Function to be measured, specified as a function handle.fis either a handle to a function that takes no input, or a handle to an anonymous function with an empty argument list.

Number of desired outputs fromf, specified as an integer. If the function specified byfhas a variable number of outputs,numOutputsspecifies which syntaxtimeituses to call the function. For example, thesvdfunction returns a single output,s, or three outputs,[U,S,V]. SetnumOutputsto1to time thes = svd(X)syntax, or set it to3to time the[U,S,V] = svd(X)syntax.

Tips

  • 以下操作导致意外输出:

    • Usingtimeitbetweentictoc
    • Usingtimeit为了计时一个函数,包括调用tictoc
    • Usingtimeitrecursively

Algorithms

timeit多次调用指定功能,并计算测量的中位数。

Introduced in R2013b

Was this topic helpful?