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

标签 python timeit

示例来自 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"))

但是如何调用带参数的函数,比如这样的函数:

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

最佳答案

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

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"))

关于python - 在带参数的函数中使用 timeit 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16924688/

相关文章:

python - Couchbase,4 个具有副本的节点(不分片),从 127.0.0.1 中选择

python - 如何使用pySpark子模块中定义的UDF?

python -m timeit : SyntaxError: from __future__ imports must occur at the beginning of the file

python - 使用 `timeit` 的 60MB 字符串测试加入列表会导致 MemoryError

Python timeit命令行错误: "SyntaxError: EOL while scanning string literal"

python - 设置 NetworkX 边长

python - PyTorch 警告关于在前向包含多个 autograd 节点时使用非完整后向钩子(Hook)

python - 仅保留 Pandas 多索引中单个索引的最后一个值(drop_duplicates)

python - timeit 返回什么时间单位?

python - timeit 通过关闭垃圾回收有什么好处?