简体   繁体   English

关于python中的timeit模块的问题

[英]Question about timeit module in python

I have a question about the timeit module in python, which is used to determine the time it takes for a piece of code to execute. 我对python中的timeit模块有疑问,该模块用于确定执行一段代码所花费的时间。

t = timeit.Timer("foo","from __main__ import foo")
str(t.timeit(1000))

What is the meaning of the argument 1000 in the above code ? 上面的代码中参数1000的含义是什么?

From the documentation : 文档中

 Timer.timeit([number=1000000]) 

Time number executions of the main statement. 主语句的时间number执行。 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. 这将执行一次setup语句,然后返回执行主语句所需的时间,以秒为单位,以浮点数为单位。 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. 将要使用的主语句,设置语句和计时器函数传递给构造函数。

As documented , the number indicates the number of times timeit should execute the specified program. 记录所示 ,该数字表示应执行指定程序的时间。

Since the first few executions can be significantly slower due to caching, and individual execution times may vary wildly, more timing runs (ie a higher value) will yield a more precise result, but also take longer. 由于缓存会导致前几次执行的速度明显变慢,并且各个执行时间可能会发生巨大变化,因此更多的计时运行(即更高的值)将产生更精确的结果,但还会花费更长的时间。

In the spirit of teaching a man to fish, just ask Python: 本着教人钓鱼的精神,只问Python:

>>> import timeit
>>> t=timeit.Timer()
>>> help(t.timeit)
Help on method timeit in module timeit:

timeit(self, number=1000000) method of timeit.Timer instance
    Time 'number' executions of the main statement.

    To be precise, this executes the setup statement once, and
    then returns the time it takes to execute the main statement
    a number of times, as a float measured in seconds.  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.

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

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