如果您对内部代码感兴趣,我将反汇编该指令以获取它映射到的CPython字节码。使用Python3:»»» def test():
return 2**3
...:
»»» dis.dis(test)
2 0 LOAD_CONST 3 (8)
3 RETURN_VALUE
好吧,看来这已经完成了输入时的计算,并存储了结果。对于2*2*2,您可以得到完全相同的CPython字节码(请随意尝试)。所以,对于求值为常数的表达式,得到的结果是相同的,这无关紧要。
如果你想要一个变量的幂怎么办?
现在得到两个不同的字节码位:»»» def test(n):
return n ** 3
»»» dis.dis(test)
2 0 LOAD_FAST 0 (n)
3 LOAD_CONST 1 (3)
6 BINARY_POWER
7 RETURN_VALUE
与»»» def test(n):
return n * 2 * 2
....:
»»» dis.dis(test)
2 0 LOAD_FAST 0 (n)
3 LOAD_CONST 1 (2)
6 BINARY_MULTIPLY
7 LOAD_CONST 1 (2)
10 BINARY_MULTIPLY
11 RETURN_VALUE
现在的问题当然是,二进制乘法是否比二进制幂运算快?
最好的办法就是利用时间。我将使用IPython%timeit魔法。下面是乘法的输出:%timeit test(100)
The slowest run took 15.52 times longer than the fastest. This could mean that an intermediate result is being cached
10000000 loops, best of 3: 163 ns per loop
为了权力The slowest run took 5.44 times longer than the fastest. This could mean that an intermediate result is being cached
1000000 loops, best of 3: 473 ns per loop
您可能希望对有代表性的输入重复此操作,但从经验上看,乘法似乎更快(但请注意前面提到的关于输出方差的警告)。
如果您想了解更多的内部信息,我建议您深入研究CPython代码。