python - Counter()+=Counter 和 Counter.update(Counter) 哪个更快?

标签 python function profiling counter operator-keyword

哪个更快? Counter()+=CounterCounter.update(Counter)

为什么一个比另一个更快?

我尝试了一些简单的分析,但我认为这不足以最终证明 Counter+=CounterCounter.update(Counter) 更快:

from collections import Counter
import time
x = Counter(['abc','def', 'abc'])
y = Counter(['xyz', 'xyz', 'uvw', 'abc'])

start = time.time()
x.update(y)
end = time.time() - start
print x
print 'update:', end
print 

x = Counter(['abc','def', 'abc'])
start = time.time()
x+=y
end = time.time() - start
print x
print 'plus:', end

[输出]:

Counter({'abc': 3, 'xyz': 2, 'def': 1, 'uvw': 1})
update: 4.48226928711e-05

Counter({'abc': 3, 'xyz': 2, 'def': 1, 'uvw': 1})
plus: 2.28881835938e-05

最佳答案

Counter.update() 方法的设计速度更快。 __add__() 方法做了更多的工作,因为它必须消除非负值:

# heart of the update() loop in Python 2:
for elem, count in iterable.iteritems():
    self[elem] = self_get(elem, 0) + count

# heart of the __add__() loop in Python 2:
result = Counter()
for elem, count in self.items():
    newcount = count + other[elem]
    if newcount > 0:
        result[elem] = newcount
for elem, count in other.items():
    if elem not in self and count > 0:
        result[elem] = count
return result

如您所见,__add__ 方法做了更多的工作。

Python 3 的更高版本中还有另一个区别,它具有一个 __iadd__() 方法,该方法执行真正的就地更新,其工作量比 __add__() 少> 方法创建一个新计数器,然后进行赋值以替换旧计数器:

def __iadd__(self, other):
    for elem, count in other.items():
        self[elem] += count
    return self._keep_positive()

关于python - Counter()+=Counter 和 Counter.update(Counter) 哪个更快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22443512/

相关文章:

javascript - 根据最接近的数字返回值

python - 如何分析 python 代码和回溯

cuda - 在 NVIDIA GPU 分析中,什么是子分区、扇区和单元?

python - 为什么python在for和while循环之后使用 'else'?

javascript - 如何在 Javascript 中从外部作用域调用函数?

python - 在 Matplotlib 中重置颜色循环

python - 将另一个文件中的函数读取到 python 中的按钮中

ios - XCode 4.1 - 仪器时间分析器

python - 从汤 BeautifulSoup/Python 中删除 span 标签

python - 为什么这不起作用(sqlite,python)