Python战俘更快的求幂

示例

从命令行使用timeit模块:

> 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

内置**运算符通常派上用场,但是如果性能至关重要,请使用math.pow。但是请务必注意,即使参数为整数,pow也会返回浮点数:

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