[英]Python list pop() much slower than list[1:]
I recently wrote a quick and dirty BFS implementation, to find diamonds in a directed graph. 我最近编写了一个快速而肮脏的BFS实现,以在有向图中找到菱形。 The BFS loop looked like this: BFS循环如下所示:
while toVisit:
y = toVisit.pop()
if y in visited: return "Found diamond"
visited.add(y)
toVisit.extend(G[y])
( G
is the graph - a dictionary from node names to the lists of their neighbors) ( G
是图形-从节点名称到其邻居列表的字典)
Then comes the interesting part: I thought that list.pop()
is probably too slow, so I ran a profiler to compare the speed of this implementation with deque.pop - and got a bit of an improvement. 接下来是有趣的部分:我认为list.pop()
可能太慢了,所以我运行了一个探查器来比较此实现与deque.pop的速度-并做了一些改进。 Then I compared it with y = toVisit[0]; toVisit = toVisit[1:]
然后,我将其与y = toVisit[0]; toVisit = toVisit[1:]
y = toVisit[0]; toVisit = toVisit[1:]
, and to my surprise, the last implementation is actually the fastest one. y = toVisit[0]; toVisit = toVisit[1:]
,令我惊讶的是,最后一个实现实际上是最快的。
Does this make any sense? 这有道理吗? Is there any performance reason to ever use list.pop()
instead of the apparently much faster two-liner? 是否有任何性能原因要使用list.pop()
而不是明显快得多的两层线?
You have measured wrong. 你测错了。 With cPython 2.7 on x64, I get the following results: 在x64上使用cPython 2.7,我得到以下结果:
$ python -m timeit 'l = list(range(10000))' 'while l: l = l[1:]'
10 loops, best of 3: 365 msec per loop
$ python -m timeit 'l = list(range(10000))' 'while l: l.pop()'
1000 loops, best of 3: 1.82 msec per loop
$ python -m timeit 'import collections' \
'l = collections.deque(list(range(10000)))' 'while l: l.pop()'
1000 loops, best of 3: 1.67 msec per loop
使用生成器来提高性能
python -m timeit 'import itertools' 'l=iter(xrange(10000))' 'while next(l, None): l,a = itertools.tee(l)'
1000000 loops, best of 3: 0.986 usec per loop
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.