【问题标题】:Python timeit and program outputPython timeit 和程序输出
【发布时间】:2012-06-04 16:31:22
【问题描述】:

有没有办法使用timeit函数同时输出函数结果和处理时间?

我现在正在使用

timer = Timer('func()', 'from __main__ import func')
print timer.timeit(1)

但这只是输出时间而不是程序输出,它在结束时返回一些东西。我希望它输出

FuncOutputGoesHere 13.2897528935

在同一行。

理想情况下,我希望能够通过运行 N 次来获取程序的平均值,然后输出程序结果及其平均时间(总共输出一次)

【问题讨论】:

  • 我似乎看到人们推荐 timeit 和人们推荐 time.time() 之间有很多偏差。哪个更好?
  • timeit 使用 time.time(),除非您在 Windows 上,否则它将使用 time.clock(更准确)。
  • 那么timeit会为我提供最准确的信息吗?
  • 我的回答为您提供了与timeit 使用的相同的代码。它会同样准确。
  • 更新了我的答案;如果你不止一次运行它无论如何,为什么不再次运行它来捕获返回值呢?

标签: python time timeit


【解决方案1】:

两种选择:

  1. 在您的定时代码中包含“打印”。丑陋,但是嘿。

    timer = Timer('print func()', 'from __main__ import func')
    print timer.timeit(1)
    
  2. 如果你只是运行你的函数一次,那么就完全不用timeit模块,直接用同样的方法给代码计时:

    import sys
    import time
    
    if sys.platform == "win32":
        # On Windows, the best timer is time.clock()
        default_timer = time.clock
    else:
        # On most other platforms the best timer is time.time()
        default_timer = time.time
    
    t0 = default_timer()
    output = func()
    t1 = default_timer()
    print output, t1 - t0
    

如果您想多次运行代码并产生输出,为什么不在timeit 函数之外运行代码一次?无论如何,您已经不止一次调用它了:

    timer = Timer('func()', 'from __main__ import func')
    print timer.timeit(100),
    print func()

【讨论】:

    【解决方案2】:

    timeit 模块执行传递的语句。你可以只打印函数的结果:

    timer = Timer('print func()', 'from __main__ import func')
    print timer.timeit(1)
    

    【讨论】:

    • 这将打印一百万次,或者无论语句执行的频率如何,并且还将 I/O 开销计入计时中。
    • @delnan:他运行 timer.timeit(1)... 随心所欲。 :-P
    • @MartijnPieters 我不知道如何多次运行它而不输出多次;我也认为我需要将结果除以运行时数,因为它似乎是聚合的。最好运行几次以获得平均值并输出一次。
    • 是的,它汇总了总运行时间。请参阅 timeit 文档。
    猜你喜欢
    • 1970-01-01
    • 2013-01-18
    • 2013-01-17
    • 2014-10-04
    • 2018-03-08
    • 2016-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多