简体   繁体   English

在带参数的函数中使用timeit模块

[英]Using timeit module in a function with arguments

Example from documentation 文档示例

def test():
    """Stupid test function"""
    L = []
    for i in range(100):
        L.append(i)

if __name__ == '__main__':
    import timeit
    print(timeit.timeit("test()", setup="from __main__ import test"))

but how to call a function with parameters, for example, a function like this: 但是如何使用参数调用函数,例如,像这样的函数:

def test(some_object):
    """Stupid test function"""
    L = []
    for i in range(100):
        L.append(some_object)

err, if I get your question right, you're just looking for that? 呃,如果我的问题是对的,你只是在找那个?

anobj = 42 # where it can be whatever object
def test(foo):
    pass # do something with foo

if __name__ == '__main__':
    import timeit
    print(timeit.timeit("test(anobj)", setup="from __main__ import test, anobj"))

Here's one solution that worked for me in this exact situation, as long as your arguments are not tremendous matrices or anything like that. 这是一个在这种情况下对我有用的解决方案,只要你的论证不是巨大的矩阵或类似的东西。


Let's say that I want to test a function foo(a,b,c) with values that I've initialized inside of my main function. 假设我想用我在main函数中初始化的值来测试函数foo(a,b,c)。 I can make the call to the following without changing my code, 我可以在不改变代码的情况下调用以下内容,

timeit.Timer('foo({},{},{})'.format(a,b,c), "from __main__ import foo")

If your arguments are strings, then you must re-introduce the quotes around the values: 如果您的参数是字符串,那么您必须重新引入值的引号:

timeit.Timer('foo("{}","{}","{}")'.format(a,b,c), "from __main__ import foo")

As a final warning, you must consider that your arguments will pass through the str() format, which may cause them to lose precision and integrity of various kinds. 作为最后的警告,您必须考虑您的参数将通过str()格式,这可能会导致它们失去各种精度和完整性。 Please check your inputs if you use this method! 如果您使用此方法,请检查您的输入!

You want to use: 你想用:

def main():
    import timeit
    print(timeit.timeit("test(some_object)")) # don't need to use the 'setup'

def test(my_object):
    lst = []
    for i in range(100):
        lst.append(my_object)

if __name__ == '__main__':
    main()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM