我有一个关于python中timeit模块的问题,该模块用于确定一段代码执行所需的时间。
t = timeit.Timer("foo","from __main__ import foo")
str(t.timeit(1000))
上面代码中参数 1000 的含义是什么?
从文档中:
Timer.timeit([number=1000000])
主语句的时间
number
执行。这将执行一次 setup 语句,然后返回多次执行主语句所需的时间,以秒为单位测量为浮点数。参数是循环的次数,默认为一百万。将要使用的主语句、设置语句和计时器函数传递给构造函数。
如文档所述,该数字表示 timeit 应执行指定程序的次数。
由于缓存的原因,前几次执行可能会显着变慢,并且各个执行时间可能变化很大,因此更多的计时运行(即更高的值)将产生更精确的结果,但也需要更长的时间。
本着教人钓鱼的精神,问 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.