2016-08-28 49 views
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快,有時它們速度相同。爲什麼會發生?

+0

'開放的(路徑)爲f:返回f.readlines()' – jonrsharpe

回答

3

這些結果都是幾乎一致,考慮到你的CPU(很可能)也在做其他事情。由於您一次運行每個「測試代碼」,這一事實使得您的計時無關緊要。

您應該使用timeit來執行這些測試。它會多次運行代碼,並輸出只有幾個最快的結果,這會給你一個更好的比較。

def build1(): 
    seq = [] 
    fin = open('words.txt') 
    for line in fin: 
     word = line.strip() 
     seq.append(word) 
    fin.close() 
    return seq 

def build2(): 
    seq = [] 
    fin = open('words.txt') 
    for line in fin: 
     word = line.strip() 
     seq += [word] 
    fin.close() 
    return seq 


import timeit 
print(timeit.Timer(build1).repeat(number=1000)) 
print(timeit.Timer(build2).repeat(number=1000)) 

這將運行build1build2 1000次,並返回最佳的3對每個功能。這些結果比您看到的結果更一致,幾乎總是build1快於build2。我已經使用了1024行的文本文件進行這些測試。

[0.538437745654897, 0.5233988257550134, 0.523436147804647] 
[0.5738405088861467, 0.5879328483021968, 0.574590215558163] 

讓我們的時間以正確的方式做到這一點:

def fast(): 
    with open('words.txt') as f: 
     return [line.strip() for line in f.readlines()] 

import timeit 
print(timeit.Timer(fast).repeat(number=1000)) 
>> [0.48617474650164105, 0.46462499504316523, 0.45692032442191644] 
相關問題