On V 9.01 on windows 7, all 64 bit.
I am sure I am missing something simple here, but I used all the tricks of the trade that I know about, and read docs, and do not see anything that helps.
Here is a compiled function made to speed up some computation.
When this function is put inside Plot
or Table
it resort back to being slow at the speed of the original uncompiled function speed.
Using Evaluate
gives an error.
Here is a MWE (This function takes about one minute to evaluate and compile, sorry that is what I am using, but it is only one line, and takes one minute to compile)
ClearAll[f, g, g0, x, b, a];
f = Function[{##} /. {x_, b_, a_} :>Piecewise[{{Exp[-b*(-Log[x])^a], 0. < x <= 1.}}]];
g = InverseFunction[f, 1, 3];
g0 = Compile[{{x, _Real}, {a, _Integer}, {b, _Integer}}, g[x, a, b]]
Timing[g0[.1, 3, 2]]
(* {0.156001, 0.416409} *)
and
Timing[g0[#, 3, 2] & /@ Range[0, 1, .1]]
It is fast now. Uncompiled version takes more than 60 seconds for each one computation.
But when in a table, it becomes slow again, using the original version? or for some other reason
Table[Timing[g0[x, 3, 2]], {x, 0, .1, .1}]
(* {{61.308393, 0.00258519}, {61.323993, 0.416409}} *)
Evaluate
gives error and still slow
Table[Evaluate[g0[x, 3, 2]], {x, 0, .1, .1}]
(*CompiledFunction::cfsa: "Argument x at position 1 should be a
"machine-size real number " *)
Direct use of Table is too slow, same as above.
Table[g0[x, 3, 2], {x, 0, .1, .1}]
Same issue with Plot
. Can't use Evaluate
and if I do not, it is slow. Using Compiled-False
did not help (since g0
is already compiled), it is still slow
Plot[g0[x, 3, 2], {x, 0, 1}, Method -> {Compiled -> False}]; (*slow*)
Plot[g0[x, 3, 2], {x, 0, 1}, Method -> {Compiled -> False}, Evaluated -> False];
Plot[g0[x, 3, 2], {x, 0, 1}, Evaluated -> False]; (*slow*)
How can one use Compiled function in Table
and Plot
without it being slow?
Is it one of those HoldRest
, HoldFirst
issues or I am missing something more basic here?
CompilePrint[g0]
hasMainEvaluate[ Hold[g][ R0, I0, I1]]
andFirst@Timing[g0[#, 3, 2] & /@ Range[0, 1, .1]]
gives 0.16, same as when usingg
directly. EDIT: Ran it again, now the timing was very slow... $\endgroup$g1[v_?NumericQ, b_Integer, a_Integer] := Block[{x}, x /. FindRoot[f[x, b, a] == v, {x, .5}]]
which takes ~2s to plot, if you plan to use it often you could also interpolate it. $\endgroup$