The secrets of operator.add

June Kim junaftnoon at nospamplzyahoo.com
Fri Dec 8 12:27:26 EST 2000


>>> profile.run('map(lambda x:x+1,range(5000))')

         5002 function calls in 0.584 CPU seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
     5000    0.257    0.000    0.257    0.000 <string>:1(<lambda>)
        1    0.325    0.325    0.582    0.582 <string>:1(?)
        1    0.002    0.002    0.584    0.584 profile:0(map(lambda
x:x+1,range(5000)))
        0    0.000             0.000          profile:0(profiler)


>>> profile.run('map(operator.add,(1,)*5000,range(5000))')

         2 function calls in 0.022 CPU seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.021    0.021    0.021    0.021 <string>:1(?)
        1    0.002    0.002    0.022    0.022
profile:0(map(operator.add,(1,)*5000,range(5000)))
        0    0.000             0.000          profile:0(profiler)


"Jacek Generowicz" <jmg at ecs.soton.ac.uk> wrote in message
news:g08zpq51vy.fsf at scumbag.ecs.soton.ac.uk...
> 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