List.count()与Counter()性能对比 [英] list.count() vs Counter() performance
本文介绍了List.count()与Counter()性能对比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在尝试查找字符串中一串字符的频率时,为什么对4个不同的字符运行string.count(Character)4次会产生比使用集合更快的执行时间(使用time.time())。Counter(字符串)?
背景: 给定由字符串表示的一系列移动。有效移动包括R(右)、L(左)、U(上)和D(下)。如果移动序列将我带回原点,则返回True。否则,返回FALSE。
# approach - 1 : iterate 4 times (3.9*10^-6 seconds)
def foo1(moves):
return moves.count('U') == moves.count('D') and moves.count('L') == moves.count('R')
# approach - 2 iterate once (3.9*10^-5 seconds)
def foo2(moves):
from collections import Counter
d = Counter(moves)
return d['R'] == d['L'] and d['U'] == d['D']
import time
start = time.time()
moves = "LDRRLRUULRLRLRLRLRLRLRLRLRLRL"
foo1(moves)
# foo2(moves)
end = time.time()
print("--- %s seconds ---" % (end - start))
这些结果与我预期的相反。我的理由是,第一种方法应该花费更长的时间,因为字符串要迭代4次以上,而在第二种方法中,我们只迭代一次。会不会是因为库调用开销?
推荐答案
Counter
理论上速度较快,但固定开销较高,特别是与str.count
相比,str.count
可以直接比较内存扫描底层C数组,list.count
需要对每个元素进行丰富的比较;将moves
转换为单字符的list
几乎是本地测试中foo1
时间的三倍,从448 ns降至1.3μs(而foo2
实际上更快,从5.6μs降至5.48μs)。
其他问题:
这篇关于List.count()与Counter()性能对比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文