Ich verwende Python 3.5.2. Ich habe eine Funktion getestet, die Wörter aus einer Datei liest und sie zu einer Liste macht. Ich habe zwei Versionen gemacht: eine mit der Append-Methode und die andere mit der Verkettung. Dann machte ich eine andere Funktion, um die Zeit zu testen, die sie nehmen.Inkonsistente Ergebnisse beim Testen der Geschwindigkeiten von append und verketten
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)
Ich habe es ein paar Mal getestet und hier ist meine Ausgabe.
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
Die meiste Zeit ist build1 schneller als build2. Aber manchmal ist build2 schneller als build1 und manchmal haben sie die gleiche Geschwindigkeit. Warum passiert das?
'mit offenem (Pfad) als f: return f.readlines()' – jonrsharpe