2016-09-23 68 views
-1

我創建了一個函數,它接受另一個函數作爲參數並計算該特定函數的運行時間。但是當我運行它,我似乎無法理解爲什麼這不起作用。有人知道爲什麼嗎?計算給定函數的運行時間python

import time 
import random 
import timeit 
import functools 

def ListGenerator(rangeStart,rangeEnd,lenth): 
sampleList = random.sample(range(rangeStart,rangeEnd),lenth) 
return sampleList 


def timeit(func): 
    @functools.wraps(func) 
    def newfunc(*args): 
     startTime = time.time() 
     func(*args) 
     elapsedTime = time.time() - startTime 
     print('function [{}] finished in {} ms'.format(
      func.__name__, int(elapsedTime * 1000))) 
    return newfunc 

@timeit 
def bubbleSort(NumList): 
    compCount,copyCount= 0,0 

    for currentRange in range(len(NumList)-1,0,-1): 
     for i in range(currentRange): 
      compCount += 1 
      if NumList[i] > NumList[i+1]: 
       temp = NumList[i] 
       NumList[i] = NumList[i+1] 
       NumList[i+1] = temp 
    # print("Number of comparisons:",compCount) 



NumList = ListGenerator(1,200,10) 
print("Before running through soriting algorithm\n",NumList) 
print("\nAfter running through soriting algorithm") 
bubbleSort(NumList) 
print(NumList,"\n") 
for i in range (0, 10, ++1): 
print("\n>Test run:",i+1) 
bubbleSort(NumList) 
compCount = ((len(NumList))*((len(NumList))-1))/2 
print("Number of comparisons:",compCount) 

運行時的屏幕截圖 enter image description here

+0

你有'timeit'作爲模塊和裝飾者的名字。這可以嗎? –

+0

是的,我已經改變了裝飾器的名稱,並再次運行它。錯誤仍然存​​在:/ @vishes_shell –

+1

只需運行'bubbleSort(list(range(10000)))' –

回答

0

它看起來像代碼只是執行非常快。在bubbleSort,我增加了一個額外的for循環執行的比較另一10000時間:

@timeit 
def bubbleSort(NumList): 
    compCount,copyCount= 0,0 

    for i in range(10000): 
     for currentRange in range(len(NumList)-1,0,-1): 
      for i in range(currentRange): 
       compCount += 1 
       if NumList[i] > NumList[i+1]: 
        temp = NumList[i] 
        NumList[i] = NumList[i+1] 
        NumList[i+1] = temp 

現在的結果是:

('Before running through soriting algorithm\n', [30, 18, 144, 28, 155, 183, 50, 101, 156, 26]) 

After running through soriting algorithm 
function [bubbleSort] finished in 12 ms 
([18, 26, 28, 30, 50, 101, 144, 155, 156, 183], '\n') 
('\n>Test run:', 1) 
function [bubbleSort] finished in 12 ms 
('Number of comparisons:', 45) 
('\n>Test run:', 2) 
function [bubbleSort] finished in 8 ms 
('Number of comparisons:', 45) 
('\n>Test run:', 3) 

等等@vishes_shell點在評論這一點,以及。

+1

嘿非常感謝:) –