三种方法, 在生成字典的过程中,对字典的key的默认值进行设置,
消耗时间的长短测试
方法以及代码
#coding: utf8
"""
三种方法, 在生成字典的过程中,对字典的key的默认值进行设置
花费时间的长短测试
"""
import time
def testDict(string_times):
s = "hello" * string_times
print( "string len is {0}".format(len(s)))
# 方法1
d1 = dict()
t1 = time.time()
for ch in s:
d1.setdefault(ch, 0)
d1[ch] += 1
t2 = time.time()
print("d1 = ", t2 - t1)
# 方法2
d2 = dict()
for ch in s:
d2[ch] = d2.get(ch, 0) + 1
t3 = time.time()
print("d2 = ", t3 - t2)
# 方法3
import collections
d3 = collections.defaultdict(int)
for ch in s:
d3[ch] += 1
t4 = time.time()
print("d3 = ", t4 - t3)
if d1 == d2 and d1 == d3 and d2 == d3:
print "dictionary value equal ", d1 == d2, d1 == d3, d2 == d3
else:
print "error"
print("-" * 30)
def main():
testDict(100)
testDict(1000)
testDict(10000)
testDict(100000)
if __name__ == "__main__":
main()
生成结果
结论在生成字典的过程中:
对于遍历较大的序列,collections.defaultdict(int) 的方法, 在效率上有较为明显的优势。
对于遍历较小的序列,字典的get和setdefault方法效率上接近,且两个方法优collections.defaultdict(int)
“`
string len is 500
(‘d1 = ‘, 0.0)
(‘d2 = ‘, 0.0)
(‘d3 = ‘, 0.005000114440917969)
dictionary value equal True True True
string len is 5000
(‘d1 = ‘, 0.0009999275207519531)
(‘d2 = ‘, 0.0009999275207519531)
(‘d3 = ‘, 0.0010001659393310547)
dictionary value equal True True True
string len is 50000
(‘d1 = ‘, 0.013000011444091797)
(‘d2 = ‘, 0.011999845504760742)
(‘d3 = ‘, 0.006000041961669922)
dictionary value equal True True True
string len is 500000
(‘d1 = ‘, 0.127000093460083)
(‘d2 = ‘, 0.11800003051757812)
(‘d3 = ‘, 0.06399989128112793)
dictionary value equal True True True
——————————“`