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.


1 Answer 1


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

enter image description here

ls2[t_] := Quantity[10, "Nanometers"]/t
Plot[ls2[Quantity[t, "Seconds"]]/Quantity[1, "SpeedOfLight"], {t, 0, 10}, 
     Evaluated -> True] // Timing

enter image description here

ls3[t_] := Quantity[10, "Nanometers"]/t
Plot[Evaluate[ls3[Quantity[t, "Seconds"]]/Quantity[1, "SpeedOfLight"]], 
    {t, 0, 10}] // Timing

enter image description here

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

enter image description here

  • $\begingroup$ The answer is even nicer than I would have hoped for, thousand of thanks! $\endgroup$ Commented May 18, 2015 at 9:11
  • $\begingroup$ @AlexeyBobrick, my pleasure. Thank you for the accept. $\endgroup$
    – kglr
    Commented May 18, 2015 at 9:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.