[Tutor] power of 2.718282

Kent Johnson kent37 at tds.net
Tue Jan 13 23:42:26 CET 2009


On Tue, Jan 13, 2009 at 5:09 PM, Marc Tompkins <marc.tompkins at gmail.com> wrote:

> Apparently nothing at all is wrong with it:
> C:\Python25\Lib>python timeit.py -s "import math" "x=math.exp(10)"
> 1000000 loops, best of 3: 0.678 usec per loop
>
> C:\Python25\Lib>python timeit.py -s "from math import e" "x=e**10"
> 1000000 loops, best of 3: 0.411 usec per loop

Using ** beats exp() because there is an explicit bytecode for
exponentiation so no function call is needed.

Careful, though; on my computer about 1/2 of the difference between
these two is due to the different style of import:

C:\Project\Mango> python -m timeit -s "import math" "x=math.exp(10)"
1000000 loops, best of 3: 0.467 usec per loop

C:\Project\Mango> python -m timeit -s "from math import exp" "x=exp(10)"
1000000 loops, best of 3: 0.352 usec per loop

C:\Project\Mango> python -m timeit -s "from math import e" "x=e**10"
1000000 loops, best of 3: 0.259 usec per loop

Name lookup and function call are both expensive in Python. Using a
constant instead of the variable e is substantially faster:

C:\Project\Mango> python -m timeit "x=2.718182**10"
10000000 loops, best of 3: 0.0399 usec per loop

Kent


More information about the Tutor mailing list