栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在程序中使用Python的“ timeit”,但功能与命令行相同?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在程序中使用Python的“ timeit”,但功能与命令行相同?

当您

timeit
从命令行这样调用时:

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

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

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

如果看一下源代码,您会发现该

main
函数可以带有一个
args
参数:

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

因此,确实可以

timeit
从程序内部运行,并且行为与从CLI运行时完全相同。只需提供您自己的,
args
而不是将其设置为
sys.argv[1:]

import timeitimport shlexdef foo():    total = 0    for i in range(10000):        total += i**3    return totaltimeit.main(args=shlex.split("""-s'from __main__ import foo' 'foo()'"""))

将打印类似

100 loops, best of 3: 7.9 msec per loop

不幸的是,

main
打印到控制台,而不是返回每个循环的时间。所以,如果你想以编程方式使用的结果,也许是最简单的方法是通过复制来启动该
main
功能,然后修改它-
改变打印代码,改为返回
usec


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

utils_timeit.py

import timeitdef 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

您可以在如下脚本中使用它:

import timeitimport utils_timeit as UTdef foo():    total = 0    for i in range(10000):        total += i**3    return totalnum, timing = UT.timeit_auto(setup='from __main__ import foo', stmt='foo()')print(num, timing)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/669148.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号