gpt4 book ai didi

python - python中带参数的时间函数

转载 作者:行者123 更新时间:2023-11-28 16:26:49 26 4
gpt4 key购买 nike

我有一个以字符串作为参数的函数,它返回两个列表

例如

def return_words(string):
return list1, list2

显然中间有代码。我希望能够为各种字符串准确计时这个函数,因为我需要在输入长字符串时提高效率。

对不起,如果这是一个微不足道的问题,因为我是 python 的新手。

谢谢

最佳答案

您可以使用timeit 模块并在timeitsetup 参数中传递参数:

from timeit import timeit


inp = """
def return_words(string):
return list1, list2
return_words(string)
"""

for s in list_of_inputs:
print '{}'.format(s), '->', timeit(stmt=inp,
number=1000000,
setup="string = '{}'".format(s))

演示:

inp = """
def return_words(string):
return [i for i in string if i.isdigit()]

return_words(string)
"""

list_of_inputs = ['inputstring1', 'inp2']

for s in list_of_inputs:
print '{}'.format(s), '->', timeit(stmt=inp,
number=1000000,
setup="string = '{}'".format(s))

输出:

inputstring1 -> 0.986068964005
inp2 -> 0.548749923706

请注意 timeit 也接受一个函数作为您代码中定义的第一个参数,但您不能将参数传递给它。在这种情况下,最好创建一个包装器,它将使用相对参数调用您的函数。阅读http://pythoncentral.io/time-a-python-function/了解更多信息。

关于python - python中带参数的时间函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35909029/

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