从程序中使用Python的`timeit`,但其功能与命令行相同?

问题描述 投票:6回答:2

例如,documentation says

但是请注意,timeit仅在使用命令行界面时才会自动确定重复次数。

是否有一种方法可以在Python脚本中调用它,并自动确定重复次数,而只返回最短的次数?

python timeit
2个回答
8
投票

当您从命令行这样调用timeit时:

python -mtimeit -s'import test' 'test.foo()'

timeit模块称为脚本。特别地,main函数称为:

if __name__ == "__main__":
    sys.exit(main())

[如果您查看the source code,您会发现main函数可以采用args参数:

def main(args=None):    
    if args is None:
        args = sys.argv[1:]

因此,确实可以从程序中运行timeit,其行为与从CLI运行时完全相同。只需提供自己的args,而不是将其设置为sys.argv[1:]

import timeit
import shlex

def foo():
    total = 0
    for i in range(10000):
        total += i**3
    return total

timeit.main(args=shlex.split("""-s'from __main__ import foo' 'foo()'"""))

将打印类似内容

100 loops, best of 3: 7.9 msec per loop

[不幸的是,main打印到控制台,而不是返回每个循环的时间。因此,如果要以编程方式使用结果,也许最简单的方法是从复制the main function开始然后对其进行修改-更改打印代码以改为返回main


OP的示例:如果将此放置在usec中:

utils_timeit.py

您可以在这样的脚本中使用它:

import timeit
def timeit_auto(stmt="pass", setup="pass", repeat=3):
    """
    http://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 >= 0.2:
            break
    r = t.repeat(repeat, number)
    best = min(r)
    usec = best * 1e6 / number
    return number, usec

0
投票

从Python 3.6开始,import timeit import utils_timeit as UT def foo(): total = 0 for i in range(10000): total += i**3 return total num, timing = UT.timeit_auto(setup='from __main__ import foo', stmt='foo()') print(num, timing) 对象具有timeit.Timer函数,该函数公开如何确定timeit.Timer用于命令行执行。

© www.soinside.com 2019 - 2024. All rights reserved.