exec'ing functions

Peter Otten __peter__ at web.de
Fri Dec 10 03:19:37 EST 2004


Mel Wilson wrote:

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

It's not that bad as most of the extra time is spend on compiling the
string.

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

def fib7(n, c=compile("a, b, i = 0, 1, n", "<nofile>", "exec")):
    exec c
    while i > 0:
        a, b = b, a+b
        yield a
        i -= 1

[Python 2.3]
$ timeit.py -s"from fib import fib5 as fib" "list(fib(100))"
10000 loops, best of 3: 143 usec per loop
$ timeit.py -s"from fib import fib6 as fib" "list(fib(100))"
10000 loops, best of 3: 208 usec per loop
$ timeit.py -s"from fib import fib7 as fib" "list(fib(100))"
10000 loops, best of 3: 151 usec per loop

Peter





More information about the Python-list mailing list