1
我正在使用Python 3.5.2。我正在測試一個函數,它將讀取文件中的單詞並將它們放入列表中。我做了兩個版本:一個用append方法,另一個用concatenate操作。然後,我做了另一個功能來測試他們所花費的時間。當測試追加和連接的速度時,結果不一致
import time
def build1(path):
seq = []
fin = open(path)
for line in fin:
word = line.strip()
seq.append(word)
fin.close()
return seq
def build2(path):
seq = []
fin = open(path)
for line in fin:
word = line.strip()
seq += [word]
fin.close()
return seq
def test(f, p):
start = time.time()
f(p)
stop = time.time()
print('Duration: %fs' %(stop - start))
path = 'C:/Users/neem/Desktop/words.txt'
test(build1, path)
test(build2, path)
我測試了幾次,這裏是我的輸出。
C:\Users\neem\AppData\Local\Programs\Python\Python35-32>python Programs/Test.py
Duration: 0.171600s
Duration: 0.156000s
C:\Users\neem\AppData\Local\Programs\Python\Python35-32>python Programs/Test.py
Duration: 0.171600s
Duration: 0.202800s
C:\Users\neem\AppData\Local\Programs\Python\Python35-32>python Programs/Test.py
Duration: 0.171600s
Duration: 0.202801s
C:\Users\neem\AppData\Local\Programs\Python\Python35-32>python Programs/Test.py
Duration: 0.171600s
Duration: 0.202800s
C:\Users\neem\AppData\Local\Programs\Python\Python35-32>python Programs/Test.py
Duration: 0.171600s
Duration: 0.187200s
C:\Users\neem\AppData\Local\Programs\Python\Python35-32>python Programs/Test.py
Duration: 0.187200s
Duration: 0.187200s
C:\Users\neem\AppData\Local\Programs\Python\Python35-32>python Programs/Test.py
Duration: 0.187200s
Duration: 0.140400s
C:\Users\neem\AppData\Local\Programs\Python\Python35-32>python Programs/Test.py
Duration: 0.187200s
Duration: 0.187200s
C:\Users\neem\AppData\Local\Programs\Python\Python35-32>python Programs/Test.py
Duration: 0.171600s
Duration: 0.187200s
大多數情況下,build1比build2快。但有時build2比build1快,有時它們速度相同。爲什麼會發生?
'開放的(路徑)爲f:返回f.readlines()' – jonrsharpe