How can I make this piece of code even faster?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Jul 21 06:31:42 EDT 2013


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


How exactly are you timing the code?



-- 
Steven



More information about the Python-list mailing list