How can I make this piece of code even faster?

pablobarhamalzas at gmail.com pablobarhamalzas at gmail.com
Sun Jul 21 12:48:36 CEST 2013


El domingo, 21 de julio de 2013 12:31:42 UTC+2, Steven D'Aprano  escribió:
> 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?

I'm timing the whole program with cProfile. Removing math.sqrt() from a function and using **(1/2) instead cut the execution time for a significant amount (~0.035 to ~0.020). I can't see another explanation for the speed increase...



More information about the Python-list mailing list