# How to create fast functions based on units?

Using units is a good means for rapidly developing code, since it provides some error control.

Hovewer, using Mathamatica functions containing units appears to be copmutationally inefficient.

Example: I have a function:

LambdaSpeed[t_] := Quantity[10, "Nanometers"]/t


It gives some dimensional output for dimensional input, which I would like to plot in units of $c$:

Plot[LambdaSpeed[Quantity[t, "Seconds"]]/
Quantity[1, "SpeedOfLight"], {t, 0, 10}] // Timing


Effectively, plotting a hyperbola in chosen units takes 6.3 seconds on my machine.

The problem is that Mathematica applies the same costly operation of unit conversion many times.

In developing I sometimes end up developing code in dimensional form and then redefining the same functions, assuming a chosen unit system.

Question: Is there a way to use functions containing units in high-performance calculations?

I would imagine this would require defining automatic rules, which would call an interpreter for each given unit conversion just once and the rest would be evaluated directly without interpreter.

Using the option Evaluated->True or wrapping the first argument of Plot with Evaluated gives a 100x speed-up:

ls1[t_] := Quantity[10, "Nanometers"]/t
Plot[ls1[Quantity[t, "Seconds"]]/Quantity[1, "SpeedOfLight"], {t, 0, 10}] // Timing ls2[t_] := Quantity[10, "Nanometers"]/t
Plot[ls2[Quantity[t, "Seconds"]]/Quantity[1, "SpeedOfLight"], {t, 0, 10},
Evaluated -> True] // Timing ls3[t_] := Quantity[10, "Nanometers"]/t
Plot[Evaluate[ls3[Quantity[t, "Seconds"]]/Quantity[1, "SpeedOfLight"]],
{t, 0, 10}] // Timing Update: Better yet, define the function to be plotted outside Plot wrapped with Evaluate:

ls4[t_] := Evaluate[Quantity[10, "Nanometers"]/Quantity[t, "Seconds"]/
Quantity[1, "SpeedOfLight"]]

Plot[ls4[t], {t, 0, 10}] // Timing • The answer is even nicer than I would have hoped for, thousand of thanks! May 18, 2015 at 9:11
• @AlexeyBobrick, my pleasure. Thank you for the accept.
– kglr
May 18, 2015 at 9:13