Timeit 模块 - 将参数传递给 python timeit 模块

Timeit module -passing arguments to python timeit module

来自 python timeit 模块我想检查打印以下内容需要多少时间,如何操作,

import timeit
x = [x for x in range(10000)]
timeit.timeit("print x[9999]")
d=[{i:i} for i in x]
timeit.timeit("print d[9999]")

NameError: global name 'x' is not defined
NameError: global name 'd' is not defined

根据 the docs:

To give the timeit module access to functions you define, you can pass a setup parameter which contains an import statement

在您的情况下,例如:

timeit.timeit('print d[9999]', 
              setup='from __main__ import d')

以下是您如何操作的示例:

import timeit

x = [x for x in range(10000)]
d = [{i: i} for i in x]

for i in [x, d]:
    t = timeit.timeit(stmt="print(i[9999])", number=100, globals=globals())
    print(f"took: {t:.4f}")

输出:

took: 0.0776
took: 0.0788

请注意我添加了 number=100,所以它每次测试运行 100 次。默认为 1,000,000 次。