【问题标题】:Measuring performance of multiple functions through a function in python通过python中的函数测量多个函数的性能
【发布时间】:2020-05-08 23:04:50
【问题描述】:

我有多个函数,我想测量每个函数的性能并将经过的时间存储在一个列表中。我对在时间测量函数中运行这些函数有点困惑:

def time_measure(function):
    import time
    t = time.process_time()
    # run function here
    elapsed_time = time.process_time() - t
    output = []
    output.append(elapsed time)
    return output

或者我想我可以为每个功能运行time_measure 并分别获取时间测量值。我有五个函数要运行。

如何在time_measure函数中运行函数,并将函数设置为参数?

【问题讨论】:

  • 这能回答你的问题吗? Python time measure function
  • 如果这是为了进行基准测试,您可能需要检查 stdlib 的 timeit 模块。如果那是为了分析,最好使用真正的分析器......
  • @brunodesthuilliers 谢谢。

标签: python-3.x performance function time


【解决方案1】:

iPython中很容易测量一个函数的时间,你不需要编写任何代码。

启动 iPython 并输入您的代码:

import time 

def SomeFunction(): 
    time.sleep(0.337)
    return

现在您可以对该函数的调用计时:

%timeit SomeFunction()
339 ms ± 1.72 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

如果要对多个语句计时,请使用%%timeit

%%timeit 
     SomeFunction() 
     SomeFunction() 
     SomeFunction() 

1.02 s ± 2.23 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多