I have a function that I want to Compile into C for speed. Inside this function is a certain long expression called x, which has been computed earlier in a Mathematica session. However, if you call x naively inside the code, then you are referring to an "external variable" and so ordinary Wolfram Language code is used instead.
See below. The second version is 100 times faster because it got properly compiled into C. How can I include x in the code without literally copying-and-pasting a huge expression, which muddies up my notebook?
x = Sin[i^2]*Cos[i] (* A fairly long complicated expression *);
compiledsum1 = Compile[{{NumPoints, _Integer}},
Block[
{i, sum = 0.0},
For[i = 0, i < NumPoints, i++, sum += x;];
sum
], CompilationTarget -> "C"];
compiledsum2 = Compile[{{NumPoints, _Integer}},
Block[
{i, sum = 0.0},
For[i = 0, i < NumPoints, i++, sum += Sin[i^2]*Cos[i];];
sum
], CompilationTarget -> "C"];
Timings:
compiledsum1[100000] // Timing
{0.841049, 223.296}
compiledsum2[100000] // Timing
0.006448, 223.296
"InlineExternalDefinitions" -> True
, seeCompilationOptions
inCompile
$\endgroup$