指定时间段的时间

时间:2014-04-22 17:01:14

标签: python timeit

我知道我可以使用这样的时间:

timeit.timeit("f(x)", "from __main__ import f", number=100000)

这将重复f() 100000次。

但是,我想做这样的事情:

timeit.timeit("f()", "from __main__ import f", duration=5000)

这将在必要时重复f(),直到达到5秒。

timeit 中是否存在类似内容?或者我是否必须自行制作一个while循环?

2 个答案:

答案 0 :(得分:0)

不,没有这样的选择。查看this open issue

这是在timeit.main中完成的方式,当您运行类似python -m timeit ...的内容时调用它(此处仅包含相关部分):

if number == 0:
    # determine number so that 0.2 <= total time < 2.0
    for i in range(1, 10):
        number = 10**i
        try:
            x = t.timeit(number)
        except:
            t.print_exc()
            return 1
        if verbose:
            print "%d loops -> %.*g secs" % (number, precision, x)
        if x >= 0.2:
            break

您可以轻松地将其修改为在“total_time”之后停止。

答案 1 :(得分:0)

从命令行运行时,

python -mtimeit -s'from script import f, x' 'f(x)'

timeit脚本找到调用该函数至少0.2秒所需的迭代次数。 Endolith has coalesced that code到函数:

def timeit_auto(stmt="pass", setup="pass", repeat=3, duration=0.2):
    """
    https://stackoverflow.com/q/19062202/190597 (endolith)
    Imitate default behavior when timeit is run as a script.

    Runs enough loops so that total execution time is greater than 0.2 sec,
    and then repeats that 3 times and keeps the lowest value.

    Returns the number of loops and the time for each loop in microseconds
    """
    t = timeit.Timer(stmt, setup)

    # determine number so that 0.2 <= total time < 2.0
    for i in range(1, 10):
        number = 10 ** i
        x = t.timeit(number)  # seconds
        if x >= duration:
            break
    r = t.repeat(repeat, number)
    best = min(r)
    usec = best * 1e6 / number
    return number, usec

timeit code in the standard library可以在这里找到。