【问题标题】:Time module in python does not measure the time difference between two lines, shows always 0python中的时间模块不测量两行之间的时间差,总是显示0
【发布时间】:2020-01-11 13:55:23
【问题描述】:

我正在尝试测量 Python 中 contains() 函数的性能。我通过使用python的时间模块来做到这一点。

代码如下:

from time import time

def contains(collection, target):
    return target in collection


def performance():

    n = 1024

    while n < 50000000:
        sorted = range(n)
        now  = time()

        # code whose performance
        #
        # is to be evaluated
        contains(sorted, -1)

        done = time()

        print(n, (done-now)*1000)
        n *= 2

performance()

我遇到的问题是,即使我增加了小数位,我也总是观察到 0 时差。我缺少 time() 模块中的一些标志。我也在使用python 3.7。我应该说我的机器并没有那么快,可以在两行之间传递 0 时间。

这是输出:

1024 0.0
2048 0.0
4096 0.0
8192 0.0
16384 0.0
32768 0.0
65536 0.0
131072 0.0
262144 0.0
524288 0.0
1048576 0.0
2097152 0.0
4194304 0.0
8388608 0.0
16777216 0.0
33554432 0.0

Process finished with exit code 0

【问题讨论】:

  • in 对于范围 afaik 来说非常快,因为它可以使用数学而不是线性检查来检查。考虑改用timeit。无论如何,您都会得到更准确的结果。
  • 尝试获取时间差以连续运行 100 次而不是一次
  • @MohammadAthar timeit 会自动执行此操作。
  • @Erindy,有ipython的经验吗?

标签: python arrays python-3.x time


【解决方案1】:

我遇到的问题是,即使我增加了小数位,我总是观察到 0 时差。

这是因为您正在计时的操作实际上是瞬时的。

range() 返回a range object,而不是列表。这些对象可以像列表一样迭代,但它们使用优化的操作实现,如in 和索引。在这种情况下,in 的实现只需要检查该数字是否在范围的最小值和最大值之间——此操作的速度与范围的大小无关。

如果您想用大型列表测试函数的性能,您需要将range 转换为list,例如

sorted_numbers = list(range(n))

(您应该避免使用名称sorted 来表示变量,因为there is a builtin function with that name。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-21
    • 1970-01-01
    • 2019-11-11
    • 2019-01-11
    相关资源
    最近更新 更多