Queues vs List

MRAB python at mrabarnett.plus.com
Fri Dec 25 18:33:30 EST 2009


Rodrick Brown wrote:
> Was reading the official python document and I noticed they mentioned 
> queues being more efficient for adding/removing elements vs list so I 
> wrote a quick test the validate this claim and I wasn't very impressed 
> by the results it seems queues are just slightly faster so my question 
> to the list, is deque used much in python over general lists? 
> 
> 
>   1 #!/usr/bin/python
>   2 
>   3 import time
>   4 from collections import deque
>   5 
>   6 nameList = ["Eric","John","Michael"]
>   7 #queue = deque(["Eric","John","Michael"])
>   8 queue = deque(nameList)
>   9 
>  10 def buildItems_q(q,n,mode):
>  11     start = 0
>  12     end = 0
>  13 
>  14     if mode == 'q':
>  15         start = time.time()
>  16         for r in xrange(n):
>  17             queue.append("Terry_%s" % r)
>  18         end = time.time()
>  19 
>  20         while q.pop() is not None:
>  21             try:
>  22                 q.pop()
>  23             except IndexError:
>  24                 pass
>  25             break
>  26     else:
>  27         start = time.time()
>  28         for r in xrange(n):
>  29             q.append("Terry_%s" % r)
>  30         end = time.time()
>  31 
>  32         while q.pop() is not None:
>  33             try:
>  34                 q.pop()
>  35             except IndexError:
>  36                 pass
>  37             break
>  38 
>  39     return (end - start)
>  40 
>  41 if __name__ == "__main__":
>  42     size = 10000000
>  43     mode = 'list'
> 44     runtime = buildItems_q(queue,size,mode)
>  45     print "Total run time: %f (%s)" % (runtime,mode)
>  46 
>  47     mode = 'Queue'
>  48     runtime = buildItems_q(queue,size,mode)
>  49     print "Total run time: %f (%s)" % (runtime,mode)
> 
> 
> rbrown at laptop:~/code/python$ python queue.py 
> Total run time: 5.169290 (list)
> Total run time: 5.112517 (Queue)
> 
You're passing either 'list' or 'Queue' into buildItems_q(), but testing
for 'q'.



More information about the Python-list mailing list