Slowness in compile()/eval()
Alex Martelli
aleax at aleax.it
Thu Jan 17 09:14:32 EST 2002
"Pedro Rodriguez" <pedro_rodriguez at club-internet.fr> wrote in message
news:pan.2002.01.17.14.19.06.888663.2742 at club-internet.fr...
> Hello,
>
> while investigating on lazy evaluations, I found these strange
> results while doing some timings. I expected that using :
> d = eval(code)
> where
> code = compile("i+i", '<string>', 'eval')
This uses a GLOBAL variable named 'i'...
> should give an execution time of the same magnitude as :
> d = f(i)
> where
> def f(i): return i+i
...while this uses a LOCAL one.
> it turns out to be almost 4x slower.
>
> Investigating with the dis module, I noticed that the result of
> compile uses LOAD_NAME where a function uses LOAD_FAST. Is this
> due to local namespace lookup ?
Right. Local is faster than global, exactly because it can
be loaded without a lookup (LOAD_NAME).
Change your function to:
def f(): return i+i
and the time difference should just about go away.
> It turns out that using something like (with some tweaks) :
> code = compile("def f(i):\n return i*i\n", '<string>', 'exec')
> eval(code)
> gives the expected computation time.
>
> I think I must be missing something on evaluation, but what ?
I don't think you're necessarily missing anything.
Alex
More information about the Python-list
mailing list