Why are functions atomic?

Duncan Booth duncan.booth at invalid.invalid
Thu May 3 05:51:25 EDT 2007


aleax at mac.com (Alex Martelli) wrote:

>> Is there a reason for using the closure here?  Using function
>> defaults seems to give better performance:
> 
> What measurements show you that...?
> 
...
> 
> brain:~ alex$ python -mtimeit -s'import powi; p=powi.powerfactory1(3)'
> 'p(27)'
> 1000000 loops, best of 3: 0.485 usec per loop
> 
> brain:~ alex$ python -mtimeit -s'import powi; p=powi.powerfactory2(3)'
> 'p(27)'
> 1000000 loops, best of 3: 0.482 usec per loop

Your own benchmark seems to support Michael's assertion although the 
difference in performance is so slight that it is unlikely ever to 
outweigh the loss in readability.

Modifying powi.py to reduce the weight of the function call overhead and 
the exponent operation indicates that using default arguments is faster, 
but you have to push it to quite an extreme case before it becomes 
significant:

def powerfactory1(exponent, plus):
   def inner(x):
       for i in range(1000):
           res = x+exponent+plus
       return res
   return inner

def powerfactory2(exponent, plus):
   def inner(x, exponent=exponent, plus=plus):
       for i in range(1000):
           res = x+exponent+plus
       return res
   return inner

C:\Temp>\python25\python -mtimeit -s "import powi; p=powi.powerfactory1
(3,999)" "p(27)"
10000 loops, best of 3: 159 usec per loop

C:\Temp>\python25\python -mtimeit -s "import powi; p=powi.powerfactory2
(3,999)" "p(27)"
10000 loops, best of 3: 129 usec per loop



More information about the Python-list mailing list