我正在尝试使用python的timeit模块,它似乎在timeit源代码中有错误(尽管这似乎不正确)。
下面是正在运行的代码片段:def recordCuckoo(amtElements, loadFactor):
'''
Determines the average lookup speed in seconds of a cuckoo hash table
with @amtElements elements and a load factor of @loadFactor
'''
mySetup = '''
import Statistics
import random
import hashingLibrary
from CuckooHashing import *
'''
controlStatement = "Statistics.timeCuckooControl(" + str(amtElements) + "," + str(loadFactor) + ")"
testStatement = "Statistics.timeCuckoo(" + str(amtElements) + "," + str(loadFactor) + ")"
controlTime = timeit.timeit(controlStatement, setup=mySetup, number=1)
testTime = timeit.timeit(testStatement, setup=mySetup, number=1)
lookupTime = (testTime - controlTime)/1000000
print ("The average lookup time for a cuckoo table with {0} elements and a load factor of {1} was:".format(amtElements, loadFactor))
print (lookupTime)
return lookupTime
if __name__ == "__main__":
recordCuckoo(100, 0.5)
当我运行它时,我收到以下错误:
Traceback (most recent call last):
File "C:Python34CuckooHashingStatistics.py", line 308, in <module>
recordCuckoo(100, 0.5)
File "C:Python34CuckooHashingStatistics.py", line 267, in recordCuckoo
controlTime = timeit.timeit(controlStatement, setup=mySetup, number=1)
File "C:Python34libtimeit.py", line 213, in timeit
return Timer(stmt, setup, timer).timeit(number)
File "C:Python34libtimeit.py", line 122, in __init__
code = compile(src, dummy_src_name, "exec")
File "<timeit-src>", line 9
_t0 = _timer()
^
IndentationError: unindent does not match any outer indentation level
我知道错误很可能在键盘和椅子之间,但是我收到的错误似乎表明timeit模块中有一个不合适的空格/制表符。这是怎么回事?
您可以这样定义mySetup
变量:
mySetup = '''
import Statistics
import random
import hashingLibrary
from CuckooHashing import *
'''
如果你考虑到这一点,这根本不是问题。但是,这些行实际上出现在函数声明中:
def recordCuckoo(amtElements, loadFactor):
mySetup = '''
import Statistics
import random
import hashingLibrary
from CuckooHashing import *
'''
因此,实际上mySetup
的含量如下:
'''
import Statistics
import random
import hashingLibrary
from CuckooHashing import *
'''
可以看到,在import
行前面有一个缩进,这使得它们无效(因为它们在执行时没有预期的缩进)。因此,您应该以不同的方式设置setup变量:
def recordCuckoo(amtElements, loadFactor):
mySetup = '''
import Statistics
import random
import hashingLibrary
from CuckooHashing import *
'''
或者像这样的:
def recordCuckoo(amtElements, loadFactor):
mySetup = 'n'.join((
'import Statistics',
'import random',
'import hashingLibrary',
'from CuckooHashing import *'
))
以下测试可以工作:
timeit.timeit('a+3', setup='a=1', number=10000)
timeit.timeit('a+3 -float(2n)', setup='a=1', number=10000)
timeit.timeit(' a+3 -float(2n)', setup='a=1', number=10000)
但这失败了,你的错误:
timeit.timeit('a+3', setup=' a=1', number=10000)
注意setup中的空格。您可以通过传递mySetup.strip()
来消除它。
在运行有问题的函数之前打印变量总是一个好主意,但是你感到困惑是正确的,错误是绝对神秘的。