So I have what I assumed to be a textbook example of where compiling my code would be faster. I just make a little ellipse in the complex plane;
oval[θ_, a_] := N[1/2 (Cos[π (1 - θ)] + I a Sin[π (1 - θ)] + 1)]
ovalC := Compile[ {{θ, _Real}, {a, _Real}}
, (Cos[π (1 - θ)] + I a Sin[π (1 - θ)] + 1)/2
]
But then when I run the compiled code and it is consistently about four times slower than the uncompiled code
oval[0.2, 1] // Timing
ovalC[0.2, 1] // Timing
{0.000075, 0.0954915 + 0.293893 I}
{0.000268, 0.0954915 + 0.293893 I}
My understanding is that I have made up a numerical-value only function and then compiling it should be quicker as it shouldn't need to do so much eg. checking for symbolic/numerical expressions etc. that Mathematica normally does.
Am I misunderstanding what the compile function is meant to do?
:=
you use to defineovalC
. Since evaluation is delayed it's recompiling the function every time it's called instead of once when it's defined and then using the faster code. If I useovalC=Compile[...]
I see a slight improvement over the uncompiled function. $\endgroup$ – N.J.Evans Nov 6 '17 at 12:57CompilationTarget -> "C"
, and if you're going to run it over a lot of arguments,RuntimeAttributes -> Listable
(and then run it over lists). $\endgroup$ – aardvark2012 Nov 6 '17 at 13:18Mathematica =!= Pascal
. I also had quite a hard time learning that... $\endgroup$ – Henrik Schumacher Nov 6 '17 at 18:42