Python Language Math Module Pow for faster exponentiation


Using the timeit module from the command line:

> python -m timeit 'for x in xrange(50000): b = x**3'
10 loops, best of 3: 51.2 msec per loop
> python -m timeit 'from math import pow' 'for x in xrange(50000): b = pow(x,3)' 
100 loops, best of 3: 9.15 msec per loop

The built-in ** operator often comes in handy, but if performance is of the essence, use math.pow. Be sure to note, however, that pow returns floats, even if the arguments are integers:

> from math import pow
> pow(5,5)