使用迭代的函数以及n为偶数时n =(axa) n / 2和n为奇数时[[axa) (n-1)/ 2 ] xa的事实是否会比python中的内置函数产生更好的结果3。
No, you will not be able to out perform Python built-in operations. The reason is fairly simple, those built-in operations run C code, in the case of CPython. You will not beat C code by writing Python code.
If we think about your case specifically, your solution would require to instantiate multiple integer or float objects, do comparions, multiply, all that in Python ! This is something the built-in power operator does not do, as Python has an instruction that computes the power in C and only instantiate one object, which is the value that you want.
We can see that by using dis
to see python bytecode.
>>> import dis
>>> dis.dis('a**b')
1 0 LOAD_NAME 0 (a)
2 LOAD_NAME 1 (b)
4 BINARY_POWER
6 RETURN_VALUE
>>> dis.dis("""
r = 1
while b > 1:
if b % 2:
b = (b - 1) / 2
a *= a
r *= a
else:
b /= 2
a *= a
r *= a""")
2 0 LOAD_CONST 0 (1)
2 STORE_NAME 0 (r)
3 4 SETUP_LOOP 66 (to 72)
6 LOAD_NAME 1 (b)
8 LOAD_CONST 0 (1)
10 COMPARE_OP 4 (>)
12 POP_JUMP_IF_FALSE 70
4 14 LOAD_NAME 1 (b)
16 LOAD_CONST 1 (2)
18 BINARY_MODULO
20 POP_JUMP_IF_FALSE 52
5 22 LOAD_NAME 1 (b)
24 LOAD_CONST 0 (1)
26 BINARY_SUBTRACT
28 LOAD_CONST 1 (2)
30 BINARY_TRUE_DIVIDE
32 STORE_NAME 1 (b)
6 34 LOAD_NAME 2 (a)
36 LOAD_NAME 2 (a)
38 INPLACE_MULTIPLY
40 STORE_NAME 2 (a)
7 42 LOAD_NAME 0 (r)
44 LOAD_NAME 2 (a)
46 INPLACE_MULTIPLY
48 STORE_NAME 0 (r)
50 JUMP_ABSOLUTE 6
9 52 LOAD_NAME 1 (b)
54 LOAD_CONST 1 (2)
56 INPLACE_TRUE_DIVIDE
58 STORE_NAME 1 (b)
10 60 LOAD_NAME 2 (a)
62 LOAD_NAME 2 (a)
64 INPLACE_MULTIPLY
66 STORE_NAME 2 (a)
68 JUMP_ABSOLUTE 6
70 POP_BLOCK
11 72 LOAD_NAME 0 (r)
74 LOAD_NAME 2 (a)
76 INPLACE_MULTIPLY
78 STORE_NAME 0 (r)
80 LOAD_CONST 2 (None)
82 RETURN_VALUE
I'll let you guess how disproportionately more efficient the built-in is.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.