MathGroup Archive 1997

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: When to use Compile[]

  • To: mathgroup at
  • Subject: [mg8735] Re: [mg8720] When to use Compile[]
  • From: David Withoff <withoff>
  • Date: Sat, 20 Sep 1997 22:28:02 -0400
  • Sender: owner-wri-mathgroup at

> Dear MathGroup,
> My Mathematica skills have progressed to the point that I care about
> performance tweaking as well as getting the code to work. I would be
> grateful for any thoughts group members might have about what functions
> work with Compile[] and when it should be used.
> I know that it works for basic numerical operations on numbers and lists of
> numbers, for example, the definition for the Jarque-Bera test statistic for
> normality (thanks Colin Rose for alerting me to this -- it halved the
> Timing result).
> But what about things like Solve and FindMinimum?  Or Regress? Are there
> occasions where Compiled[] matrix operations will be faster than packages
> like LinearRegression? What about list construction functions like FoldList
> and NestList? Can you use Compile[]d functions within them?

Solve and FindMinimum are already compiled code, so there is nothing
to be gained by compiling them.  The objective function in FindMinimum
is compiled automatically, but sometimes there are some efficiency
improvements to be had by compiling it yourself.  Regress in the
LinearRegression package written in the Mathematica programming language.
It could in principle be rewritten to take greater advantage of Compile,
but there is nothing to be gained by an input such as Compile[...Regress...].
And yes, NestList and FoldList can be Compile[]d.

> Does anyone have any rules of thumb about when to Compile[] and when not
> to? The Mathematica Book's coverage of this issue is a bit scanty, other
> than it being for numerical functions.

You can find out what can and cannot be compiled efficiently by looking
inside of the CompiledFunction expression that is returned by Compile.
For example:

In[1]:= f[x_] := Module[{t}, t /. FindRoot[t^2 == x, {t, 1}]]

In[2]:= g = Compile[{x}, f[x]]

Out[2]= CompiledFunction[{x}, f[x], -CompiledCode-]

In[3]:= g[2]

Out[3]= 1.41421

In[4]:= ?g

g = CompiledFunction[{_Real}, {0, 0, 2, 0, 0}, 
   {{1, 2}, {4, 1, 0}, {31, Function[{x}, f[x]], 3, 0, 1}, {9, 1}}, 
   Function[{x}, f[x]]]

shows that the CompiledFunction interpreter just calls uncompiled
evaluation (instruction {31, Function[{x}, f[x]], 3, 0, 1}) to get
a result for f[x], since f[x] is an unknown function to Compile.

There are also some notes about things that can and cannot be compiled
efficiently in the technical support section of the Wolfram Research web
site (

Dave Withoff
Wolfram Research

  • Prev by Date: Re: False result with Integrate ?
  • Next by Date: Re: Bug in pattern matching?
  • Previous by thread: When to use Compile[]
  • Next by thread: Re: When to use Compile[]