python中的Timeit模块无法正确运行

2024-03-03

我正在尝试使用 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:\Python34\CuckooHashing\Statistics.py", line 308, in <module>
    recordCuckoo(100, 0.5)
  File "C:\Python34\CuckooHashing\Statistics.py", line 267, in recordCuckoo
    controlTime = timeit.timeit(controlStatement, setup=mySetup, number=1)
  File "C:\Python34\lib\timeit.py", line 213, in timeit
    return Timer(stmt, setup, timer).timeit(number)
  File "C:\Python34\lib\timeit.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行,这使得它们无效(因为它们在执行时没有预期的缩进)。因此,您应该以不同的方式设置设置变量:

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 *'
    ))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

python中的Timeit模块无法正确运行 的相关文章

随机推荐