python timeit 是否在计数中考虑设置

Does python timeit consider setup in the count

我正在使用 python timeit 来查看函数 运行.

需要多长时间
    setup = '''from __main__ import my_func
    import random
    l = list(range(10000))
    random.shuffle(l)'''
    timeit.timeit('my_func(l)', setup=setup, number=1000)

我得到的结果比使用日期时间进行的 'normal' 检查要大。 timeit 是否也计算安装所需的时间,如果是这样 - 我如何禁用它?

docs 说:

The execution time of setup is excluded from the overall timed execution run.

Python 2.0 docs很清楚setup语句没有定时:

Time number executions of the main statement. This executes the setup statement once, and then returns the time it takes to execute the main statement a number of times, measured in seconds as a float.

但如果您不确定,请将一个大而慢的进程放入设置语句中并进行测试,看看它有什么不同。

my_func(l) 会变异 l 吗?这可能会影响时间安排。

timeit 将运行 设置一次,并在每次调用要计时的代码时重用设置创建的对象。它还可以调用代码几次以大致衡量它 运行s 的速度,并在实际计时 运行 之前选择迭代次数(尽管当您指定 运行 是你自己)。这意味着如果有初始禁食 运行,它将不会包含在计时结果中。

例如,如果 my_func() 是一个写得不好的快速排序函数,它可能 运行 当你在打乱后的列表上调用它时很快,而当你再次调用它时可能会非常非常慢(现在已排序)列表。 timeit 只会测量非常慢的调用。