【问题标题】:Speed comparison between bisect.insort function and list.index and insert functionbisect.insort 函数与 list.index 和 insert 函数的速度比较
【发布时间】:2018-12-12 02:07:25
【问题描述】:

正如 Python 文档所说,我认为 bisect 模块比 list 内置方法、索引和插入要快得多,以便将项目插入长有序列表。所以,我只是测量bisect_func()insert_func() 这两个函数的时间开销,如下面的代码。

bisect_func() 得分 1.27s 和 insert_func() 得分 1.38s,这不是一个戏剧性的时差。我的问题是,在这个例子中我是否遗漏了一些测试 bisect 效率的东西?或者 bisect 不是将项目插入有序列表的唯一有效方法?

import bisect

HAYSTACK = [n for n in range(100000000)]
NEEDLES = [0, 10, 30, 400, 700, 1000, 1100, 2200, 3600, 32000, 999999]

def bisect_func():
    for needle in reversed(NEEDLES):
        bisect.insort(HAYSTACK, needle)

def insert_func():
    for needle in reversed(NEEDLES):
        position = HAYSTACK.index(needle)
        HAYSTACK.insert(position, needle)

if __name__ == '__main__':
    import time
    start = time.time()
    # bisect_func()
    insert_func()
    end = time.time()
    print(end - start)

【问题讨论】:

  • 这不是一个公平的测试(我不知道它是否会影响总冠军)但您应该使用timeit 而不是依赖全局变量

标签: python insert bisection


【解决方案1】:

来自insort的文档:

按排序顺序插入 x。这相当于 a.insert(bisect.bisect_left(a, x, lo, hi), x) 假设 a 是 已经排序。请记住,O(log n) 搜索主要由 缓慢的 O(n) 插入步骤。

重要的部分是:请记住,O(log n) 搜索主要由缓慢的 O(n) 插入步骤支配。 所以这两种方法都是 O(n) 最后,这就是为什么它们的效率相似insort 稍好一些。

【讨论】:

    【解决方案2】:

    二分查找只会提高查找插入索引的性能。它没有改进 插入 到列表中,这两种情况下都是O(N),并且支配了这两个函数的渐近复杂度。请记住,插入基于数组的列表需要移动插入索引之后的所有元素。

    【讨论】:

      猜你喜欢
      • 2011-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 2017-02-24
      • 1970-01-01
      • 1970-01-01
      • 2012-05-04
      相关资源
      最近更新 更多