inline function call

Peter Hansen peter at engcorp.com
Wed Jan 4 10:57:15 EST 2006


Riko Wichmann wrote:
> def riskfunc(med, low, high):
>      if med != 0.0:
>          u = random()
>          try:
>              if u <= (med-low)/(high-low):
>                  r = low+sqrt(u*(high-low)*(med-low))
>              else:
>                  r = high - sqrt((1.0-u)*(high-low)*(high-med))
> 
>          except ZeroDivisionError: # case high = low
>                  r = med
>      else:
>          r = 0.0
> 
>      return r

Since math.sqrt() is in C, the overhead of the sqrt() call is probably 
minor, but the lookup is having to go to the global namespace which is a 
tiny step beyond looking just at the locals.  Using a default argument 
to get a local could make a small difference.  That is do this instead:

def riskfunc(med, low, high, sqrt=math.sqrt):

Same thing with calling random(), which is doing a global lookup first 
to find the function.

By the way, you'll get better timing information by learning to use the 
timeit module.  Among other things, depending on your platform and how 
long the entire loop takes to run, using time.time() could be given you 
pretty coarse results.

You might also try precalculating high-low and storing it in a temporary 
variable to avoid the duplicate calculations.

-Peter




More information about the Python-list mailing list