Accelerating the pace of engineering and science

• Trials

# timeit

Measure time required to run function

## Description

example

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

example

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

## Examples

expand all

### Determine Time to Obtain Current Date

Use timeit to time a function call to date. This example uses a handle to a function that accepts no input.

```f = @date;
t = timeit(f)```
```t =

1.3481e-04```

### Determine Time to Compute Matrix Summation

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.0427```

### Compare Time to Run svd with Multiple Outputs

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

```X = [1 2; 3 4; 5 6; 7 8];
f = @() svd(X);
t1 = timeit(f)```
```t1 =

1.5427e-05```

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

`t2 = timeit(f,3)`
```t2 =

2.6695e-05```

### Compare Time to Execute Custom Preallocation to Calling zeros

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.

```function mArr = preAllocFcn(x,y)
for m = 1:x
for n = 1:y
mArr(m,n) = 0;
end
end
end```

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

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

0.2004```

## Input Arguments

expand all

### f — function to be measuredfunction handle

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

### numOutputs — Number of desired outputs from finteger

Number of desired outputs from f, specified as an integer. If the function specified by f has a variable number of outputs, numOutputs specifies which syntax timeit uses to call the function. For example, the svd function returns a single output, s, or three outputs, [U,S,V]. Set numOutputs to 1 to time the s = svd(X) syntax, or set it to 3 to time the [U,S,V] = svd(X) syntax.

expand all

### Tips

• The following actions result in unexpected output:

• Using timeit between tic and toc

• Using timeit to time a function that includes calls to tic and toc

• Using timeit recursively

### Algorithms

timeit calls the specified function multiple times, and computes the median of the measurements.