The secrets of operator.add

Jacek Generowicz jmg at ecs.soton.ac.uk
Fri Dec 8 17:11:29 CET 2000


Where can I find out about the ways in which the functions in the
operator module are optimized, and how to use them to best effect in my
code ?

For example, the following bit of code:

from operator import add
from profile import run
N = 50000
run ('reduce(lambda x,y:x+y, range(N))')
run ('reduce(add, range(N))')

already throws up a surprise for me:

         50001 function calls in 1.600 CPU seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
    49999    0.840    0.000    0.840    0.000 <string>:1(<lambda>)
        1    0.720    0.720    1.560    1.560 <string>:1(?)
        0    0.000             0.000          profile:0(profiler)
        1    0.040    0.040    1.600    1.600 profile:0(reduce(lambda x,y:x+y, range(N)))


         2 function calls in 0.060 CPU seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.060    0.060    0.060    0.060 <string>:1(?)
        0    0.000             0.000          profile:0(profiler)
        1    0.000    0.000    0.060    0.060 profile:0(reduce(add, range(N)))


It looks as if multiple calls to operator.add are avoided somehow
. . . or am I failing to understand the profiler's output ?

Is there a way of getting similar advantages in

run ('map(lambda x:x+1, range(N))')  ?

Is there a Python way of currying add? 

Jacek



More information about the Python-list mailing list