MathGroup Archive 2004

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

Search the Archive

Re: Question on Compile[]

  • To: mathgroup at
  • Subject: [mg49779] Re: [mg49747] Question on Compile[]
  • From: Sseziwa Mukasa <mukasa at>
  • Date: Sat, 31 Jul 2004 03:13:59 -0400 (EDT)
  • References: <>
  • Sender: owner-wri-mathgroup at

On Jul 30, 2004, at 6:02 AM, Mark Coleman wrote:

> GThe
> computation is quite simple, Let
> cashFlow be a list of real numbers of length n and let nvec=Range[n],
> then the discounted cash flow is the sum over i=1,n of
> cashFlow(i)/(1+r)^i
> where r is a real number with 0 < r < 1.
> The final Mathematica code is:
> Clear[dcf];
> dcf[cashFlow_, rate_] := Module[{nvec = Range[Length[cashFlow]]},
>      Total[cashFlow/(1.0 + rate)^nvec]
>      ]
> On my 800 Mhz Powerbook G4, 5000 trials of this takes 3.72 seconds,
> while the compiled version takes 4.2 seconds.
> Any ideas how I can speed this up, to get the usual gains one typically
> sees in compiled code?

You can get a slight improvement by not explicitly creating a temporary 
variable which removes the need for the Module expression as well:

dcf[cashFlow_, rate_] :=
      Total[cashFlow/(1.0 + rate)^Range[Length[cashFlow]]]

My guess is that this is the fastest possible expression.  From the 
information in the Help Browser Compile has to do some extra checks at 
run time about whether a statement can be done numerically or not.  The 
expression itself is very efficient and should result in a very small 
piece of machine code which operates optimally.  Any extra work 
therefore, such as any overhead introduced by Compile will only slow it 
down.  That's my guess anyway.



  • Prev by Date: Re: uniquely change curve colors and make them darker
  • Next by Date: Re: Question about composing a complex function.
  • Previous by thread: Question on Compile[]
  • Next by thread: Re: Question on Compile[]