Python timeit和程序输出

MyN*_*han 12 python time timeit

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

现在我正在使用

timer = Timer('func()', 'from __main__ import func')
print timer.timeit(1)
Run Code Online (Sandbox Code Playgroud)

但这只是输出时间而不是程序输出,它会在结束时返回一些内容.我希望它输出

FuncOutputGoesHere 13.2897528935
Run Code Online (Sandbox Code Playgroud)

在同一条线上.

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

Mar*_*ers 16

两种选择:

  1. 在您的定时代码中加入'print'.丑,但嘿.

    timer = Timer('print func()', 'from __main__ import func')
    print timer.timeit(1)
    
    Run Code Online (Sandbox Code Playgroud)
  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
    
    Run Code Online (Sandbox Code Playgroud)

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

    timer = Timer('func()', 'from __main__ import func')
    print timer.timeit(100),
    print func()
Run Code Online (Sandbox Code Playgroud)