【问题标题】:timing two algorithms (python) using timeit or time使用 timeit 或 time 计时两个算法(python)
【发布时间】:2014-10-22 15:37:10
【问题描述】:

我在使用 time 或 timeit 函数来确定 python 中两种算法的运行时间时遇到了一些麻烦。到目前为止我有这个

def normal(sound):
  for s in getSamples(sound):
    largest=max(0,getSampleValue(s))
    amplification = 32767.0/largest
  for s in getSamples(sound):
    louder = amplification*getSampleValue(s)
    setSampleValue(s,louder)

def onlyMax(sound):
  for s in getSamples(sound):
    value=getSampleValue(s)
    if value>0:
      setSampleValue(s,32767)
    if value<=0:
      setSampleValue(s,-32768)

import time
def timetwoalgorithms(sound):
    print time.time("normal(sound)","onlyMax(sound)")

程序应该测量运行每个函数所需的时间,然后输出/打印每个程序的运行时间。

【问题讨论】:

  • 我不确定我是否完全理解 timeit 或 time 函数,但我们将不胜感激,但似乎无法在堆栈中找到答案
  • 我写了一个答案here

标签: algorithm python-2.7 audio time timeit


【解决方案1】:

time.time 给出当前时间。你想要 timeit.timeit。

print(timeit.timeit("normal(sound)"))
print(timeit.timeit("onlyMax(sound)"))

但是,您不能将局部变量传递给 timeit (how to pass parameters of a function when using timeit.Timer()),因此您可能必须简化您的函数。您可以重新实现 timeit:

def timeit(exec_s, globals={}, number=10000):
    t = time.time()
    for i in range(number):
        exec(exec_s, globals)
    return time.time() - t

然后做

print(timeit("normal(sound)", locals()))
print(timeit("onlyMax(sound)", locals()))

或根据@Martijn Pieters 的回答将变量放在模块命名空间中。 或者,将时序循环合并到主函数中:

def time2algorithms(sound, number=10000):
    t = time.time()
    for i in range(number):
        normal(sound)
    print(time.time() - t)
    t = time.time()
    for i in range(number):
        onlyMax(sound)
    print(time.time() - t)

【讨论】:

  • 好的,所以当我在函数中实现 timeit 时,我应该用函数名称替换 exec_s 吗?我收到的错误是需要一个变量。如果没有,我认为我没有处理它
  • exec_s 是一个要执行的字符串,就像timeit.timeit 一样。它可以是任何可执行的python,以字符串的形式。所以在你的情况下,它是"normal(sound)""onlyMax(sound)"。但是,如果您不想使用辅助函数,您可以将exec(exec_s, globals) 替换为normal(sound)。见编辑。
  • 这似乎现在可以工作了,但是当它尝试通过时间循环执行范围程序时,我再次收到线程死亡
【解决方案2】:

time.time() function 不接受任何参数,因为它是一个简单地返回当前时间的函数(以从特定时间点开始的秒数的形式,UNIX 纪元)。您不能使用它来比较这样的两个函数运行时。您可以使用它来测量时间流逝,方法是在运行函数之前存储值,然后将其与 time.time() 值进行比较,但这是衡量性能的糟糕方法。

timeit.timeit() function确实让您可以通过重复执行测试功能并确保至少将可能妨碍准确测量的其他因素最小化来衡量测试功能需要多少时间。但是,您一次只能测试一个这样的功能。

要测试一个函数,请传入 Python 源代码以运行该函数,并传入另一个函数来设置测试。该设置应包括导入函数:

timeit.timeit("normal(sound)", 'from __main__ import normal, sound')

other 函数再次执行此操作,并将结果相互比较。

考虑到函数会被执行多次(你可以调整多少次),所以如果函数改变了全局状态,你必须每次都重置那个状态。这也会改变您衡量性能的方式。

【讨论】:

    猜你喜欢
    • 2013-01-17
    • 2011-10-10
    • 1970-01-01
    • 2012-06-15
    • 2011-06-26
    • 2017-10-20
    • 2013-10-01
    • 1970-01-01
    • 2011-10-21
    相关资源
    最近更新 更多