用 timeit returns 两个值而不是一个值测量的字典效率

Dict efficiency measured with timeit returns two values instead of one

我正在使用 timeit 测试 defaultdict()dict.setdefault() 的效率。由于某种原因,执行timeitreturns两个值;

从集合导入默认字典 从 timeit 导入 timeit

dd = defaultdict(list)
ds = {}

def dset():
    for i in xrange(100):
        ds.setdefault(i, []).append(i)

def defdict():
    for y in xrange(100):
        dd[y].append(y)

然后我打印两个函数的执行时间,我得到了 4 个值;

print timeit('dset()', setup='from def_dict import dset')
print timeit('defdict()', setup='from def_dict import defdict')

22.3247003333
23.1741990197
11.7763511529
12.6160995785

Timeit.timeit docs says

Time number executions of the main statement. This executes the setup statement once, and then returns the time it takes to execute the main statement a number of times, measured in seconds as a float. The argument is the number of times through the loop, defaulting to one million. The main statement, the setup statement and the timer function to be used are passed to the constructor.

我在 Python 2.7。

似乎当 timeit 导入设置参数中指示的脚本时,它实际上会导致再次调用它。当我在 python-3 中使用你的代码时,它也给了我两个值,但是当它把 timeit 语句放在另一个脚本中时,它每个输出一个值。此外,如果您添加以下行:

if __name__ == "__main__":

就在您的 timeit 语句之上,这也将解决问题并且只会调用一次 timeit(每个)。

至于为什么这两个值不同,我不得不猜测第二个是最初的调用,因此在第二个 returns 之后打印并打印,这意味着它具有a) 输出到打印缓冲区的额外延迟 b) 从另一个调用到 return 的时间。