I want to compile a function in a way to keep its memory footprint down. In the example below, I am trying to compile a function f that makes three calls to bigNastyFunction. I do not want to define bigNastyFunction outside and use option "InlineExternalDefinitions" -> True because then three copies of that function will be inserted into the body of the compiled function verbatim, leading to excessive memory usage. Instead, my strategy is to define bigNastyFunction inside a Module which is inside Compile. My hope is that bigNastyFunction will be appropriately stored as a subroutine, and called by the body as needed.
SetSystemOptions["CompileOptions" -> "CompileReportExternal" -> True];
f = Compile[{{x, _Complex}},
Module[{bigNastyFunction = Function[{y}, Sin[y]]},
bigNastyFunction[x] + bigNastyFunction[x^2]^2 + 3 bigNastyFunction[x^3]
]
]
The example above doesn't work because Function is not one of the functions that can be compiled by Compile. What workaround is there to define a large (complicated) function inside the body of a Compile'd function?
ByteCountandRepeatedTiming). – Michael E2 Feb 07 '16 at 03:45bigNastyFunction = Function[{y}, Sin[y]]instead of usingCompile, thenByteCount[f]goes down from 11704 to 4560, the same as @MichaelE2 's first answer. – QuantumDot Feb 07 '16 at 11:51ByteCountas mine (more than that whenbigNastyFunctionis small) because three copies of the compiled function are stored inf. For expressions with aLeafCountup to about 500, your method is up to 20% slower than mine; from 500 or so up to 100,000, they're about the same speed; and at aLeafCountof 180,000, yours was about 10% faster. (The expressions were random plus/times combinations of elementary functions.) – Michael E2 Feb 07 '16 at 13:39FullForm@f, I noticed my answer is incorrect, it also inserts 3 copies of the (compiled) function into the body! So far I can't think out a way to define a sub routine as OP desires… – xzczd Feb 08 '16 at 14:15Compile. I'll contact Wolfram Research about it. – QuantumDot Feb 14 '16 at 11:12