python使用deque实现高性能双端队列

今天有个哥们问我点东西,是分析数据的时候,会把感兴趣的数据存入到队列里面,同时有多个线程针对数据进行操作,有些数据会往前插入,他现在的问题是后时候堵塞在insert动作。 我推荐他用deque。今天宅了一天,写了个hadoop pig的脚本,可以很容易的得出以前需要手写mapreduce的结果集合。 虽然pig的语法看起来简单,但是他毕竟是个新语法, 文档也不是太丰富 。这两天我再出个pig的简易教程,让大家也享受下pig(猪)的乐趣。O(∩_∩)O~

不扯了,话说 双端队列(deque)是一种支持向两端高效地插入数据、支持随机访问的容器。

其内部实现原理如下:

双端队列的数据被表示为一个分段数组,容器中的元素分段存放在一个个大小固定的数组中,此外容器还需要维护一个存放这些数组首地址的索引数组 ,简单的理解,你可以想成一个大的array,分拆成几段,然后主要维护一个索引表。 大家看了下面的图应该就理解了。

deque的语法很是简单,一看就懂,只是rorate乍一看搞不明白。

deque有些不错的方法,用起来挺实用的,最少对我来说,是有用的。

[指定大小,像queue]

In [1]: from collections import dequeIn [2]: dq=deque(maxlen=5)In [3]: for i in range(1,100):   ...:         dq.append(i)   ...:In [4]: dqOut[4]: deque([95, 96, 97, 98, 99], maxlen=5)In [5]:

[可以快速的做数据切割]

In [1]: import collectionsIn [2]:In [2]: d = collections.deque(xrange(10))In [3]: print 'Normal        :', dNormal        : deque([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])In [4]:In [4]: d = collections.deque(xrange(10))In [5]: d.rotate(2)In [6]: print 'Right rotation:', dRight rotation: deque([8, 9, 0, 1, 2, 3, 4, 5, 6, 7])In [7]:In [7]: d = collections.deque(xrange(10))In [8]: d.rotate(-2)In [9]: print 'Left rotation :', dLeft rotation : deque([2, 3, 4, 5, 6, 7, 8, 9, 0, 1])

记得以前做统计的时候,有个api做接受数据,然后存入队列里面。当时也没用redis,毕竟有网络io的效果,就用deque来搞的。16个线程,一块做的调度,怕会出现数据安全的问题,经过测试。 在多线程下,deque双端队列是安全的,大家可以放心搞。

import collectionsimport threadingimport timecandle = collections.deque(xrange(11))def burn(direction, nextSource):    while True:        try:            next = nextSource()        except IndexError:            break        else:            print '%8s: %s' % (direction, next)            time.sleep(0.1)    print '%8s done' % direction    returnleft = threading.Thread(target=burn, args=('Left', candle.popleft))right = threading.Thread(target=burn, args=('Right', candle.pop))left.start()right.start()left.join()right.join()

这个文章的原文是在 http://blog.xiaorui.cc ,我的文章总是被爬来爬去的。

下面是一个deque 、queue、list的性能对比,如果只是单纯的任务队列的话,又不太涉及对比,是否存在,remove的动作,那用deque再适合不过了。

import timeimport Queueimport collectionsq = collections.deque()t0 = time.clock()for i in xrange(1000000):    q.append(1)for i in xrange(1000000):    q.popleft()print 'deque', time.clock() - t0q = Queue.Queue(2000000)t0 = time.clock()for i in xrange(1000000):    q.put(1)for i in xrange(1000000):    q.get()print 'Queue', time.clock() - t0q = []t0 = time.clock()for i in xrange(1000000):    q.append(i)for i in xrange(1000000):    q.insert(0,i)print 'list ', time.clock() - t0

结果和我想的一样,deque很快,Queue也算可以,但是Queue只能做put,put的方向是不能指定的。list单纯的append算是不错的,但是如果你的应用有那种优先级的逻辑,那这样的话,你需要往前插入,用insert(0,item) 。 insert这个把item值插入到第0位,但是后面的那堆索引值,都要+1的。 这个负担可不小呀。

Deque的缺点就是remove还有判断获取索引的时候,速度有些慢, 因为他需要执行多遍deque相关联的数据块 。不像list那样,搞一遍就行。

python使用deque实现高性能双端队列

相关文章:

你感兴趣的文章:

标签云: