Why is the compiled function so slow? I have seen question 41344 but don't understand any potential relevance.
Here are the two functions for comparison
logisticMap[x0_, μ_, n_] := Module[{i},
RecurrenceTable[{x[i + 1] == μ x[i] (1 - x[i]), x[1] == x0}, x, {i, 1, n}]]
logisticMapC = Compile[{{x0, _Real}, {μ, _Real}, {n, _Integer}},
t = {x0};
For[i = 2, i <= n, i++,
AppendTo[t, μ t[[i - 1]] (1 - t[[i - 1]])]];
, CompilationTarget -> "C"];
Compiler is Visual Studio 2015 Community Edition; compiling from MMA 10.1
Timing results as follows:
Module[{i}, Timing[For[i = 1, i <= 1000, i++, logisticMap[0.1, 3.55, 1000]]]]
(* {0.468003, Null} *)
Module[{i}, Timing[For[i = 1, i <= 1000, i++, logisticMapC[0.1, 3.55, 1000]]]]
(* {20.0929, Null} *)
That is not the sort of performance change I was hoping for; can anyone suggest what is wrong and whether I can actually gain an increase in speed by compilation?
I am still a beginner with MMA, please assume minimal knowledge.
AppendTo
certainly has horrible performance, probably it calls back to Mathematica to manage your list. Create a list/array of fixed size, ideally outside the function (before calling the compiled function) and use that. $\endgroup$<< CompiledFunctionTools` CompilePrint[logisticMapC]
and note the several MainEvaluate calls. Typically if you see these you shouldn't be compiling, as you are still needing to revert to Mathematica for the call which can add more latency than you save. Not all functions are compilable. $\endgroup$Compile
, it's the toy of experienced user. Currently it's more cost-efficient for you to learn to write code in Mathematica-style. If you still insist on usingCompile
, you can begin from this answer. $\endgroup$