Python 是一門現代化的面相對象的編程語言,有著豐富的擴展庫,并具有易于學習、應用廣泛的特點。
對于python程序執行效率的分析,時間復雜度與空間復雜度同樣是適用的。在總體時間復雜度相同的情況下,我們也可以直觀的使用同一臺機器上的運行時間來做直接比較。在 python的time 模塊中有一個 time 函數,它可以在任意被調用的地方返回系統時鐘的當前時間(以秒為單位)。通過在開始和結束的時候分別調用兩次 time 函數,然后計算差值,就可以得到一個函數執行的精確秒數。
以從1到N的自然數求和為例子
import time
def Sum_1(N):
sum = 0
for i in range(1,N+1):
sum += i
return sum
def main():
N = 100000
for echo in range(5):
begin_time = time.time()
sum1 = Sum_1(N)
end_time = time.time()
print("Sum method 1 -- Echo %d -- Result %d -- Cost %f seconds."%(echo, sum1, end_time-begin_time))
if __name__ == "__main__":
main()
運行結果為:
Sum method 1 -- Echo 0 -- Result 5000050000 -- Cost 0.036053 seconds.
Sum method 1 -- Echo 1 -- Result 5000050000 -- Cost 0.032034 seconds.
Sum method 1 -- Echo 2 -- Result 5000050000 -- Cost 0.018009 seconds.
Sum method 1 -- Echo 3 -- Result 5000050000 -- Cost 0.010006 seconds.
Sum method 1 -- Echo 4 -- Result 5000050000 -- Cost 0.010509 seconds.
可以看出,Python每次運行都能得出正確的結果,而運行時間也在同一個數量級上波動。
如果我們采用高斯求和公式進行算法改進——
高斯求和公式
import time
def Sum_1(N):
sum = 0
for i in range(1,N+1):
sum += i
return sum
def Sum_2(N):
sum = (1+N)*N/2
return sum
def main():
N = 10000000
###累加求和
for echo in range(5):
begin_time = time.time()
sum1 = Sum_1(N)
end_time = time.time()
print("Sum method 1 -- Echo %d -- Result %d -- Cost %f seconds."%(echo, sum1, end_time-begin_time))
print("----------------------------------------------")
###使用高斯公式
for echo in range(5):
begin_time = time.time()
sum1 = Sum_2(N)
end_time = time.time()
print("Sum method 2 -- Echo %d -- Result %d -- Cost %f seconds."%(echo, sum1, end_time-begin_time))
if __name__ == "__main__":
main()
運行結果如下:
Sum method 1 -- Echo 0 -- Result 50000005000000 -- Cost 1.237429 seconds.
Sum method 1 -- Echo 1 -- Result 50000005000000 -- Cost 1.181615 seconds.
Sum method 1 -- Echo 2 -- Result 50000005000000 -- Cost 1.044307 seconds.
Sum method 1 -- Echo 3 -- Result 50000005000000 -- Cost 1.056946 seconds.
Sum method 1 -- Echo 4 -- Result 50000005000000 -- Cost 1.041368 seconds.
----------------------------------------------
Sum method 2 -- Echo 0 -- Result 50000005000000 -- Cost 0.000000 seconds.
Sum method 2 -- Echo 1 -- Result 50000005000000 -- Cost 0.000998 seconds.
Sum method 2 -- Echo 2 -- Result 50000005000000 -- Cost 0.000000 seconds.
Sum method 2 -- Echo 3 -- Result 50000005000000 -- Cost 0.000000 seconds.
Sum method 2 -- Echo 4 -- Result 50000005000000 -- Cost 0.000000 seconds.
可以看出,高斯公式對于大數累加求和更為有利,這是符合常識的。
從以上的例子里我們也能感受到,python對于大數不需要做單獨的處理,這也是python廣泛應用于科學計算的原因之一。