我正在使用三个函数readFile,prepDict和test进行速度测试。测试只是prepDict(readFile)。然后,我使用timeit模块运行了很多次。

当我将循环数增加10倍时,功能prepDict所需的时间要长100倍左右,但是使用功能prepDict的功能测试仅增加了10倍。

这里是功能和测试。

def readFile(filepath):
    tempDict = {}
    file = open(filepath,'rb')
    for line in file:
        split = line.split('\t')
        tempDict[split[1]] = split[2]
    return tempDict

def prepDict(tempDict):
    for key in tempDict.keys():
        tempDict[key+'a'] = tempDict[key].upper()
        del tempDict[key]
    return tempDict

def test():
    prepDict(readFile('two.txt'))

if __name__=='__main__':
    from timeit import Timer
    t = Timer(lambda: readFile('two.txt'))
    print 'readFile(10000): ' + str(t.timeit(number=10000))

    tempDict = readFile('two.txt')
    t = Timer(lambda: prepDict(tempDict))
    print 'prepDict (10000): ' + str(t.timeit(number=10000))

    t = Timer(lambda: test())
    print 'prepDict(readFile) (10000): ' + str(t.timeit(number=10000))

    t = Timer(lambda: readFile('two.txt'))
    print 'readFile(100000): ' + str(t.timeit(number=100000))

    tempDict = readFile('two.txt')
    t = Timer(lambda: prepDict(tempDict))
    print 'prepDict (100000): ' + str(t.timeit(number=100000))

    t = Timer(lambda: test())
    print 'prepDict(readFile) (100000): ' + str(t.timeit(number=100000))


我得到的结果如下:

readFile(10000): 0.61602914474
prepDict (10000): 0.200615847469
prepDict(readFile) (10000): 0.609288647286
readFile(100000): 5.91858320729
prepDict (100000): 18.8842101717
prepDict(readFile) (100000): 6.45040039665


如果我多次运行它,我会得到类似的结果。为什么prepDict会增加约100倍,而prepDict(readFile)仅会增加10倍,即使使用prepDict函数也是如此?

two.txt是带有以下数据点的表格分隔文件:

Item    Title   Hello2
Item    Desc    Testing1232
Item    Release 2011-02-03

最佳答案

这里的问题是您的prepDict函数扩展了输入。每次您依次调用它时,都会处理更多数据。而且该数据呈线性增长,因此,第10000次运行所需时间大约是第10,000次。*

调用test时,每次都会创建一个新的字典,因此时间是恒定的。

您可以通过每次更改prepDict测试以使其在新的dict副本上运行而非常容易地看到这一点:

t = Timer(lambda: prepDict(tempDict.copy()))




顺便说一句,您的prepDict实际上并没有随number呈指数增长**,只是二次增长。通常,当某些事物以超线性方式增长时,并且您想要估算算法成本时,确实需要获得两个以上的数据点。



*并非如此-只有在字符串和哈希操作(线性增长)所花费的时间开始淹没其他所有操作(所有常数)所花费的时间后,它才开始线性增长。

**您在这里没有提及指数增长的任何内容,但是在your previous question中您提到了,因此您可能在实际问题中做出了相同的假设。

关于python - 速度测试导致奇怪的行为。在一个实例中乘以100的时间,在另一个实例中仅乘以10的时间,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17199108/

10-12 17:57