As Fabian said, it's hard to be faster than math.sqrt
. The reason is that it calls the correspond function from the C library, with CPython.
However, you can speed things up by removing the overhead of attribute lookup:
from math import sqrt
Each subsequent call to sqrt will not have to look it up in the math module, which saves execution time:
print sqrt(2)
Here are timing numbers, from the fastest to the slowest (Python 2.6.5, Mac OS X 10.6.3): sqrt
is faster than **0.5
:
lebigot@weinberg ~ % python -m timeit -s 'from math import sqrt; x = 2' 'sqrt(x)'
1000000 loops, best of 3: 0.207 usec per loop
lebigot@weinberg ~ % python -m timeit -s 'x = 2' 'x**0.5'
1000000 loops, best of 3: 0.226 usec per loop
lebigot@weinberg ~ % python -m timeit -s 'import math; x = 2' 'math.sqrt(x)'
1000000 loops, best of 3: 0.268 usec per loop
Note that the timing tests calculate the square root of a variable. They do not calculate a constant like 2**0.5
, because 2**0.5
is pre-calculated, in CPython:
import dis
def f():
return 2**0.5
print dis.dis(f)
prints
2 0 LOAD_CONST 3 (1.4142135623730951)
3 RETURN_VALUE
where you see the constant float sqrt(2) = 1.414…
If you manipulate arrays of numbers, NumPy's sqrt
is the way to go, as mentioned in another answer.