![](/img/trans.png)
[英]Why is my python 3 implementation much faster than the one I wrote in C++?
[英]Python's POW implementation much faster than my own
我正在Python3中練習快速冪算法,並針對Python的內置冪函數對其進行了測試。
為什么事實證明內置功能如此之快?
我的代碼:
def levinPOW(n, k):
res = 1
while k:
if k&1:
res *= n
n *= n
k = k >> 1
return res
import time
start = time.time()
a = levinPOW(2, 10000000)
end = time.time()
print(end-start)
start = time.time()
b = 2 ** 10000000
end = time.time()
print(end-start)
print(a==b)
結果:
0.31336236000061035
4.291534423828125e-06
True
內置函數是用C實現的,比用Python實現的要快得多。 它還可能有幾個人對其進行了速度改進。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.