简体   繁体   English

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

[英]Timeit module -passing arguments to python timeit module

from python timeit module i want to check how much time does it take to print the following , how to do so, 从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

Per the docs : 根据文档

To give the timeit module access to functions you define, you can pass a setup parameter which contains an import statement 要使timeit模块可以访问您定义的功能,可以传递一个包含导入语句的设置参数

In your case, that would be eg: 在您的情况下,例如:

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

Here is an example of how you can do it: 以下是如何执行此操作的示例:

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}")

Output: 输出:

took: 0.0776
took: 0.0788

Please notice I added number=100, so it runs 100 times each test. 请注意,我添加了number = 100,因此它每次运行100次。 By default it 1,000,000 times. 默认情况下为1,000,000次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM