gpt4 book ai didi

algorithm - 使用 timeit 或 time 计时两个算法(python)

转载 作者:行者123 更新时间:2023-12-03 02:09:18 32 4
gpt4 key购买 nike

我在使用 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)")

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

最佳答案

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

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

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

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

对另一个函数再次执行此操作,并将结果相互比较。

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

关于algorithm - 使用 timeit 或 time 计时两个算法(python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25554475/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com