关于Python中的timeit模块的问题

2 投票
3 回答
861 浏览
提问于 2025-04-16 23:09

我有一个关于Python中timeit模块的问题,这个模块用来测量一段代码执行所需的时间。

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

上面代码中的1000这个参数是什么意思呢?

3 个回答

1

为了让大家学会自我解决问题,就请问问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.
1

根据文档,这个数字表示timeit应该执行指定程序的次数。

因为前几次执行可能会因为缓存的原因变得特别慢,而且每次执行的时间可能会有很大差异,所以进行更多次的计时(也就是用更大的数字)会得到更准确的结果,但这样也会花费更多的时间。

4

来自文档

Timer.timeit([number=1000000])

这个功能是用来计算主要语句执行多少次所花的时间。它会先执行一次准备语句,然后返回主要语句执行多次所需的时间,单位是秒,结果是一个小数。你可以设置循环执行的次数,默认是执行一百万次。主要语句、准备语句和要使用的计时功能都会在创建时传入。

撰写回答