Article

Using vDSP for Vector-based Arithmetic

Increase the performance of common mathematical tasks with vDSP vector-vector and vector-scalar operations.

Overview

vDSP provides a suite of general-purpose, high-performance arithmetic functions that are alternatives to for loops and map when applying operations on arrays of floating-point values.

For example, the following code multiplies the elementwise sum of two arrays by a scalar value:

let a: [Float] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let b: [Float] = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
let c: Float = 2

let d = zip(a, b).map {
    ($0.0 + $0.1) * c
}

// d = [22.0, 44.0, 66.0, 88.0, 110.0, 132.0, 154.0, 176.0, 198.0, 220.0]

The vDSP version of the same operation runs significantly faster:

var d = [Float](repeating: .nan, count: a.count)

vDSP.multiply(addition: (a, b),
              c,
              result: &d)

// d = [22.0, 44.0, 66.0, 88.0, 110.0, 132.0, 154.0, 176.0, 198.0, 220.0]

Many vDSP functions have a variant that returns the result, for example:

let a: [Float] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let b: [Float] = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
let c: Float = 2

let d = vDSP.multiply(addition: (a, b),
                      c)

The following table summarizes the basic arithmetic functions available in vDSP. All functions are available in single- and double-precision variants.

In the Operation column, a subscript (for example, a[i]) indicates a vector, and no subscript (for example, a) indicates a scalar value.

Operation

Single-Precision Function

c[i] = a[i] + b

vDSP_vsadd

c[i] = a[i] + b[i]

vDSP_vadd

c[i] = a[i] - b[i]

vDSP_vsub

c[i] = a[i] * b

vDSP_vsmul

c[i] = a[i] * b[i]

vDSP_vmul

c[i] = a[i] / b

vDSP_vsdiv

c[i] = a / b[i]

vDSP_svdiv

o0[i] = i1[i] + i0[i]

o1[i] = i1[i] - i0[i]

vDSP_vaddsub

c[i] = a[i] / b[i]

vDSP_vdiv

d[i] = (a[i] + b[i]) * c

vDSP_vasm

d[i] = (a[i] + b[i]) * c[i]

vDSP_vam

d[i] = (a[i] - b[i]) * c

vDSP_vsbsm

d[i] = (a[i] - b[i]) * c[i]

vDSP_vsbm

d[i] = (a[i] * b[i]) + c

vDSP_vmsa

d[i] = (a[i] * b) + c[i]

vDSP_vsma

d[i] = (a[i] * b[i]) + c[i]

vDSP_vma

d[i] = (a[i] * b[i]) - c[i]

vDSP_vmsb

e[i] = (a[i] * b) + (c[i] * d)

vDSP_vsmsma

e[i] = (a[i] + b[i]) * (c[i] + d[i])

vDSP_vaam

e[i] = (a[i] * b[i]) - (c[i] * d[i])

vDSP_vmmsb

e[i] = (a[i] - b[i]) * (c[i] - d[i])

vDSP_vsbsbm

e[i] = (a[i] + b[i]) * (c[i] - d[i])

vDSP_vasbm

See Also

Signal Processing Essentials

Controlling vDSP Operations with Stride

Operate selectively on the elements of a vector at regular intervals.

Use Linear Interpolation to Construct New Data Points

Fill the gaps in arrays of numerical data using linear interpolation.

Resampling a Signal with Decimation

Reduce the sample rate of a signal, by specifying a decimation factor and applying a custom antialiasing filter.

vDSP

Perform basic arithmetic operations and common digital signal processing routines on large vectors.