How can I make this piece of code even faster?

Chris Angelico rosuav at gmail.com
Sun Jul 21 12:48:46 CEST 2013


On Sun, Jul 21, 2013 at 8:31 PM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> On Sun, 21 Jul 2013 03:19:24 -0700, pablobarhamalzas wrote:
>
>> Thank's for all the replies! I've tried some of the imporovements you
>> suggested (using math.exp() and sum() or math.fsum()). None of that made
>> the code faster, because they are functions you are calling lots of
>> times, and function calling is quite time expensive (same as x**(1/2) is
>> faster than math.sqrt(x)).
>
> You are *badly* mistaken. Not only is sqrt more accurate, but it is also
> much faster.
>
>
> [steve at ando ~]$ python3.3 -m timeit -s "x = 2.357e7" "x**0.5"
> 1000000 loops, best of 3: 0.319 usec per loop
> [steve at ando ~]$ python3.3 -m timeit -s "x = 2.357e7" -s "from math import
> sqrt" "sqrt(x)"
> 10000000 loops, best of 3: 0.172 usec per loop

Don't forget the cost of attribute lookup, which adds 50% to the
sqrt() figure. Still faster than exponentiation. (Figures from Python
3.4 alpha, but unlikely to be materially different.)

rosuav at sikorsky:~$ python3 -m timeit -s "x = 2.357e7" "x**0.5"
1000000 loops, best of 3: 0.239 usec per loop
rosuav at sikorsky:~$ python3 -m timeit -s "x = 2.357e7" -s "from math
import sqrt" "sqrt(x)"
10000000 loops, best of 3: 0.102 usec per loop
rosuav at sikorsky:~$ python3 -m timeit -s "x = 2.357e7" -s "import math"
"math.sqrt(x)"
10000000 loops, best of 3: 0.155 usec per loop

ChrisA



More information about the Python-list mailing list