Calling a function is faster than not calling it?
BartC
bc at freeuk.com
Sun May 10 17:08:25 EDT 2015
On 10/05/2015 10:58, Steven D'Aprano wrote:
> 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)))
Maybe the overheads of using eval() are significant when calling a
simple function such as your example.
When I made it do a bit more work:
def func():
a = 2
b = 3
c = 4
for i in range(50):
x=(a+b)*(a-b)/(a*c + b*c)
return (a+b)*(a-b)/(a*c + b*c)
Then the eval() call took only 3% longer rather than 100%.
--
Bartc
More information about the Python-list
mailing list