Calling a function is faster than not calling it?

Piet van Oostrum piet at vanoostrum.org
Mon Jun 22 17:49:31 EDT 2015


Steven D'Aprano <steve+comp.lang.python at pearwood.info> wrote:

> Why is calling a function faster than bypassing the function object and
> evaluating the code object itself? And not by a little, but by a lot?
>
> Here I have a file, eval_test.py:
>
> # === cut ===
> from timeit import Timer
>
> def func():
>     a = 2
>     b = 3
>     c = 4
>     return (a+b)*(a-b)/(a*c + b*c)
>
>
> code = func.__code__
> assert func() == eval(code)
>
> t1 = Timer("eval; func()", setup="from __main__ import func")
> t2 = Timer("eval(code)", setup="from __main__ import code")
>
> # Best of 10 trials.
> print (min(t1.repeat(repeat=10)))
> print (min(t2.repeat(repeat=10)))
>
> # === cut ===
>
>
> Note that both tests include a name lookup for eval, so that as much as
> possible I am comparing the two pieces of code on an equal footing.

They are not on equal footing. The first one only looks up eval, but the second actually calls eval. The overhead of calling eval is what makes the difference. To get them on equal footing you will have to insert an eval call also in the first example.

dummy = compile("0", 'string', "eval")

t1 = Timer("eval(dummy); func()", setup="from __main__ import dummy, func")
t2 = Timer("0; eval(code)", setup="from __main__ import code")

And then you'll see that t1 is slightly slower than t2.
-- 
Piet van Oostrum <piet at vanoostrum.org>
WWW: http://pietvanoostrum.com/
PGP key: [8DAE142BE17999C4]



More information about the Python-list mailing list