Main Content

timeit

Measure time required to run function

Description

example

t = timeit(f)measures the time (in seconds) required to run the function specified by the function handlef。In order to perform a robust measurement,timeitcalls the specified function multiple times and returns the median of the measurements. If the function runs fast,timeitmight call the function many times.

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。此示例使用一个函数的句柄,该函数不接受输入。

f = @date;t = timeit(f)
t = 4.3936e-05

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.0207

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

x = rand(100);f = @()svd(x);T1 = TimeIt(F)
t1 = 6.5784e-04

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

t2 = timeit(f,3)
t2 = 0.0018

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

要测量的函数,将其指定为函数句柄。f是不需要输入的函数的句柄,或者是带有空参数列表的匿名函数的句柄。

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]。放numOutputsto1to time thes = svd(X)syntax, or set it to3to time the[U,S,V] = svd(X)syntax.

Tips

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

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

Extended Capabilities

版本历史

Introduced in R2013b