]> Sound and music - Practical Considerations

Practical Considerations

Speed is critical in real-time applications, yet in some code I have seen around the web, there are obvious optimizations that were missed:

  • Reduce divisions by calculating the reciprocal once. For example, if you need to work out a/d and b/d, it is better to calculate 1 /d first and then multiply a and b by this quantity because divisions are typically much slower than multiplications. Another obvious example is computing 1 /d 2 from 1 /d: square it, rather than dividing by d. Even though a smart compiler might be able to do this, it is better to rely on yourself.

  • If you’re using math libraries to do trigonometry (rather than lookup tables), it may be worth rewriting equations that minimize the number of calls to the math libraries. For example, following the equations for the cookbook LPF directly will mean that both sin and cos must be computed. However, if an alternative derivation is used, then only tan is needed. It’s not clear to me why formulas are given in a relatively inefficient form.

  • Common subexpressions should only be computed once. For example, in the Cookbook’s LPF, it’s faster to compute the b i's (which by the way correspond to the a i's in our notation) by working out b 0 first, and then setting b 1 =2 b 0 , b 2 =b 0 .

  • Some people use the bilinear transform kz1 z+1 for some constant k. This is pointless because k gets cancelled out by the prewarping. The explanation in the Cookbook does not suffer from this problem: there, the prewarping is viewed as part of the bilinear map.

  • When coding a specific 2-pole lowpass or highpass filter, a few lookups and multiplications can be avoided by leaving the numerator of the transfer function H(z) as z 2 +2 z+1 and hardcoding this expression.

    For the cookbook LPF the filter takes the form

    y[n]=a(x[n]+2 x[n1 ]+x[n2 ]by[n1 ]cy[n2 ])

    where f s is the sampling frequency, f is the cutoff frequency, and

    t = 1 /tan(πf/f s) a = 1 /(t 2 +t/q+1 ) b = 2 2 t 2 c = t 2 t/q+1

    (Of course t 2 and t/q need only be computed once.)

    The cookbook HPF is similar:

    y[n]=a(x[n]2 x[n1 ]+x[n2 ]by[n1 ]cy[n2 ])


    t = tan(πf/f s) a = 1 /(t 2 +t/q+1 ) b = 2 2 t 2 c = t 2 t/q+1

    Cookbook bandpass:

    y[n]=a(b(x[n]x[n2 ])cy[n1 ]dy[n2 ])


    ω = 2 πf/f s e = 0.5 Wω/sin(ω) B = 2 e2 e t = tan(ω/2 ) a = 1 /(1 +t 2 +Bt) b = Bt c = 2 t 2 2 d = 1 +t 2 Bt

    W is the bandwidth in octaves. Note the value given to B is an approximation. For the bandpass filter with peak gain Q, leave b out (i.e. b=1 ). The cookbook formulas may be better since we must compute sin(ω) anyway.