MathGroup Archive 2008

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

Search the Archive

Re: Compiled function slowdown

  • To: mathgroup at
  • Subject: [mg86715] Re: Compiled function slowdown
  • From: Albert Retey <awnl at>
  • Date: Wed, 19 Mar 2008 05:25:03 -0500 (EST)
  • References: <fro384$i6b$>


> In a program I'm currently working on, I need to loop
> through a function ~100,000 times.  I thought I'd try compiling it to
> save on time.  However, it takes more than 10 times longer to run than
> the uncompiled (module) version.  Are there any general guidelines as
> to when a compiled function will be slower than its uncompiled
> counterpart in Mathematica (such as with the use of many conditional
> statements)?

When compiled functions are slower than regular code to my experience 
the reason is almost always the fact that mathematica has to jump out of 
the compiled code to execute things it can't do within the compiled 
code. Usually these are complicated subroutines which eventually perform 
symbolic calculations. It is easy to see whether your code could be 
compiled completely by looking at the compiled code, in version six this 
is just the -3rd argument of the CompiledFunction-Object:

In[267]:= fc=Compile[{x,_Real},Sin[x]]
Out[267]= CompiledFunction[{x,Blank$3204297},Sin[x],-CompiledCode-]

In[268]:= fc[[-3]]
Out[268]= {{1,5},{93,1,3,0,0,3,0,2},{2}}

if this is containing numbers only, you can be reasonably sure the code 
will be very fast. If not, it depends, but chances are big that the code 
will be slow.

Unfortunately, AFAIK, Compile can't handle nested compiled functions 
which makes it very uncomfortable to handle more complicated code. Here 
you can see that there are callbacks to the kernel for the evaluation of 
a compiled function:

In[269]:= gc=Compile[{x,_Real},Exp[fc[x]]]

In[270]:= gc[[-3]]

> I've included my function below (sorry if it's a mess;
> e1, e2 and fComp are very simple compiled functions), though a general
> response to the above question would be just fine.  Thanks!

this will also happen with your calls to e1, e2 and fComp and the first 
candidates for the slowdown of your code. Unfortunately the only 
solution I know is to do "function inlining by hand" :-). This is for 
many cases not or hardly possible and for the others a mess and only 
feasible since you can handle the code symbolically within mathematica.

I really hope someone proofs me wrong on this and I can learn how to 
handle this situation better, but for now a nestable compile would be 
high on my priority list for new features and make Compile much more 



  • Prev by Date: Re: Question on looping FindRoot
  • Next by Date: Re: How to consider BrowserCategories in Version 6.0?
  • Previous by thread: Re: Compiled function slowdown
  • Next by thread: Re: Compiled function slowdown