I obtained some long expression and need to use them with a lot of different parameters inside a simulation. However, evaluation of the expressions is pretty slow, so that I would like to speed it up. The first (and only) thing that came to my mind was Compile
. But, unfortunately, speed is not improved significantly.
This is an example of the shortest expression (unable to paste the larger ones because they exceed the limits on pastebin):
fun[tt_, sig_, time_, expon_, bShift_, lam_] = Uncompress@Import["https://pastebin.com/raw/nj83nT2b"];
funComp = Compile[{{tt, _Real}, {sig, _Real}, {time, _Real}, {expon, _Integer}, {bShift, _Real}, {lam, _Real}}, fun[tt, sig, time, expon, bShift, lam]];
fun[3.4, 10/4, 10, 3, 1.3456, Sqrt[2]] // AbsoluteTiming
(* {0.0836853, 0.045048} *)
funComp[3.4, 10/4, 10, 3, 1.3456, Sqrt[2]] // AbsoluteTiming
(* {0.0718691, 0.045048} *)
As you can see, Compile
basically has no effect. The bigger issue is that the harmful expressions I am dealing with rather take 10s to evaluate and I'd like to see one or more orders of magnitude speed up (if possible). I hope that the small example here is essentially limited by the same effect as the bigger expressions, so that it serves as a proper toy example.
Background on fun
: It essentially is composed of sums and products of Gaussians and their derivatives to higher orders (also powers of them).
Is there a way to significantly speed up the evaluation process? Potentially by more advanced usage of Compile
or some other trick? Currently this is a serious bottleneck in my simulations.
fun
by hand, have you? Please give us the code that produces this expression. If it contains manySum
: That's great because theSum
s can be more efficiently compiled as this humongous symbolic expression. Plus one might use vectorized code instead ofCompile
which may perform even better. $\endgroup$Sum
in the sense of using the corresponding MMA function. Indeed, the humongous expression was obtained "by hand" in the form of manually adding/multiplying Gaussians with certain parameters. Was "vectorized code" explicitly referring to a possible solution ofSum
s were used or is it a general idea? $\endgroup$Listable
). For example, ifa
is a list of machine-precision real or complex numbers (and a should also be a packed array),Exp[a]
will be compute much faster thanExp /@ a
orTable[ Exp[x],{x,a}]
. AndTotal[Exp[a]]
is mush faster thanSum[Exp[x], {x, a}]
. $\endgroup$