2014-01-05 109 views
0

我的设置参数在下面有什么问题?将嵌套函数导入时间

import timeit 
import random 
from copy import copy 

def shortBubbleSort(aList): 
    n = len(aList) - 1 
    iterating = True 
    while n > 0 and iterating: 
     iterating = False 
     for i in range(n): 
      if aList[i+1] < aList[i]: 
       iterating = True 
       aList[i], aList[i+1] = aList[i+1], aList[i] 
     n -= 1 
    return aList 


L = [] 
for i in range(1,500): 
    L.append(random.randrange(0,1000000)) 

x = timeit.repeat("bubbleSort(copy(L))", setup="from __main__ import bubbleSort,copy,L",repeat = 100,number = 100) 
y = (sum(x)/len(x))*100 
print(str(y)) 

我也试过如下:

  • setup="from __main__ import bubbleSort,from copy import copy"
  • setup="from __main__ import bubbleSort,copy"
  • setup="from __main__ import bubbleSort"

回溯如下:

Traceback (most recent call last): 
    File "C:\Users\Administrator\AppData\Local\ActiveState\KomodoEdit\7.1\samples\bubbleSort TimeIt.py", line 24, in <module> 
    x = timeit.repeat("bubbleSort(copy(L))", setup="from __main__ import bubbleSort,copy,L",repeat = 100,number = 100) 
    File "C:\Python32\lib\timeit.py", line 235, in repeat 
    return Timer(stmt, setup, timer).repeat(repeat, number) 
    File "C:\Python32\lib\timeit.py", line 223, in repeat 
    t = self.timeit(number) 
    File "C:\Python32\lib\timeit.py", line 195, in timeit 
    timing = self.inner(it, self.timer) 
    File "<timeit-src>", line 3, in inner 
ImportError: cannot import name bubbleSort 
+0

什么是错误? – mgilson

+2

那么,是什么让你觉得它有什么不对?你有错误吗?如果是这样,请显示完整的追踪。 – delnan

+0

好的 - 现在会添加...即使我知道这是一个错字。 – whytheq

回答

0

可能是一个错字。实际的函数名shortBubbleSort和要导入bubbleSort

在我的机器,结果是

192.437240362 
+0

+1 ....哎呦:尴尬的帽子在哪里? – whytheq

0

这是一个错字。您的功能称为shortBubbleSort,而不是bubbleSort。此作品:

x = timeit.repeat("shortBubbleSort(copy(L))", setup="from __main__ import shortBubbleSort,copy,L",repeat = 100,number = 100)