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

Tom*_*ise 4 python timeit

文档示例

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"))
Run Code Online (Sandbox Code Playgroud)

但是如何使用参数调用函数,例如,像这样的函数:

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

zmo*_*zmo 6

呃,如果我的问题是对的,你只是在找那个?

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"))
Run Code Online (Sandbox Code Playgroud)