deque python,python:deque vs列表性能比较

In python docs I can see that deque is a special collection highly optimized for poping/adding items from left or right sides. E.g. documentation says:

Deques are a generalization of stacks and queues (the name is

pronounced “deck” and is short for “double-ended queue”). Deques

support thread-safe, memory efficient appends and pops from either

side of the deque with approximately the same O(1) performance in

either direction.

Though list objects support similar operations, they are optimized for

fast fixed-length operations and incur O(n) memory movement costs for

pop(0) and insert(0, v) operations which change both the size and

position of the underlying data representation.

I decided to make some comparisons using ipython. Could anyone explain me what I did wrong here:

In [31]: %timeit range(1, 10000).pop(0)

10000 loops, best of 3: 114 us per loop

In [32]: %timeit deque(xrange(1, 10000)).pop()

10000 loops, best of 3: 181 us per loop

In [33]: %timeit deque(range(1, 10000)).pop()

1000 loops, best of 3: 243 us per loop

解决方案

Could anyone explain me what I did wrong here

Yes, your timing is dominated by the time to create the list or deque. The time to do the pop is insignificant in comparison.

Instead you should isolate the thing you're trying to test (the pop speed) from the setup time:

In [1]: from collections import deque

In [2]: s = range(1000)

In [3]: d = deque(s)

In [4]: s_append, s_pop = s.append, s.pop

In [5]: d_append, d_pop = d.append, d.pop

In [6]: %timeit s_pop(); s_append(None)

10000000 loops, best of 3: 115 ns per loop

In [7]: %timeit d_pop(); d_append(None)

10000000 loops, best of 3: 70.5 ns per loop

That said, the real differences between deques and list in terms of performance are:

Deques have O(1) speed for appendleft() and popleft() while lists have O(n) performance for insert(0, value) and pop(0).

List append performance is hit and miss because it uses realloc() under the hood. As a result, it tends to have over-optimistic timings in simple code (because the realloc doesn't have to move data) and really slow timings in real code (because fragmentation forces realloc to move all the data). In contrast, deque append performance is consistent because it never reallocs and never moves data.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值