exec'ing functions

Mel Wilson mwilson at the-wire.com
Fri Dec 10 00:10:12 CET 2004


In article <5SPtd.210910$HA.146444 at attbi_s01>,
Steven Bethard <steven.bethard at gmail.com> wrote:
>Jeff Shannon wrote:
>> I was referring to functions which have an internal exec statement, not
>> functions which are created entirely within an exec -- i.e., something
>> like this:
>
>Thanks for the clarification.  Here's the results for some functions
>with internal exec statements:
>
> > cat fib.py
>def fib1(n):
>     a, b = 0, 1
>     while True:
>         a, b = b, a + b
>         yield a
>
>
>exec """\
>def fib2(n):
>     a, b = 0, 1
>     while True:
>         a, b = b, a + b
>         yield a
>"""
>
>def fib3(n):
>     a, b = 0, 1
>     while True:
>         exec "a, b = b, a + b"
>         yield a
>
>def fib4(n):
>     exec "a, b = 0, 1"
>     while True:
>         exec "a, b = b, a + b"
>         yield a
>
> >
> > python -m timeit -s "import fib" "fib.fib1(100)"
>1000000 loops, best of 3: 0.71 usec per loop
>
> > python -m timeit -s "import fib" "fib.fib2(100)"
>1000000 loops, best of 3: 0.678 usec per loop
>
> > python -m timeit -s "import fib" "fib.fib3(100)"
>1000000 loops, best of 3: 0.826 usec per loop
>
> > python -m timeit -s "import fib" "fib.fib4(100)"
>1000000 loops, best of 3: 0.821 usec per loop
>
>I'm not sure I'd say they're *much* slower, but you're right; they're
>definitely slower.

   The thing is, that once you drop local-namespace
optimization, the entire function gets slowed down, possibly
by 40%:



def fib5 (n):
    a, b, i = 0, 1, n
    while i > 0:
        a, b = b, a+b
        yield a
        i -= 1


def fib6 (n):
    exec "a, b, i = 0, 1, n"
    while i > 0:
        a, b = b, a+b
        yield a
        i -= 1



f:\home\mwilson\projects\python>python  e:\bin\python23\lib\timeit.py -s "import
 fib" "[i for i in fib.fib5(100)]"
1000 loops, best of 3: 1.95e+003 usec per loop

f:\home\mwilson\projects\python>python  e:\bin\python23\lib\timeit.py -s "import
 fib" "[i for i in fib.fib6(100)]"
100 loops, best of 3: 2.82e+003 usec per loop


        Regards.    Mel.



More information about the Python-list mailing list