sorry for posting multiple questions about compile, but this is giving me some headache lately. This time my question is about using globally defined variables in a compile statement.
The problem is that when I define a compiled function that uses a global variable like this:
a = 1; (*global variable*)
GlobalVariableCompile = Compile[{{n, _Integer}}, For[i = 1, i < n, i++, a + Cos[i*Pi] + Sin[i*Pi]]];
The function is way slower then the noncompiled version:
GlobalVariable[n_] := For[i = 1, i < n, i++, a + Cos[i*Pi] + Sin[i*Pi]];
which can be easily verified by calling for example:
AbsoluteTiming[GlobalVariableCompile[100000];]
AbsoluteTiming[GlobalVariable[100000];]
What is the reason for this and how can I fix it?
My current solution:
My solution right now is to define an additional parameter of the compiled function and pass the global variable a
, then everything is very fast as expected (way faster than the noncompiled version):
GlobalVariableCompile = Compile[{{n, _Integer},{a, _Real}}, For[i = 1, i < n, i++, a + Cos[i*Pi] + Sin[i*Pi]]];
AbsoluteTiming[GlobalVariableCompile[100000,a];]
a
value? If that is the case you could rebuild the compiled function when it is called. $\endgroup$Compile
, except perhaps the one by you, which is not exactly the same. It may be good to have a separate question discussing this, and what happens when the variables are not localized, and why. $\endgroup$Compile
than I am. $\endgroup$Module
orBlock
insideCompile
). If this is not done, those variables are considered global by Mathematica. They are then not compiled, and every time they are accessed, there is a call to the main evaluator, which is the reason for the slowness. $\endgroup$