字典key默认值的设置方法及其测试结果
2016-08-10 10:53
183 查看
三种方法, 在生成字典的过程中,对字典的key的默认值进行设置,
消耗时间的长短测试
对于遍历较大的序列,collections.defaultdict(int) 的方法, 在效率上有较为明显的优势。
对于遍历较小的序列,字典的get和setdefault方法效率上接近,且两个方法优collections.defaultdict(int)
“`
string len is 500
(‘d1 = ‘, 0.0)
(‘d2 = ‘, 0.0)
(‘d3 = ‘, 0.005000114440917969)
(‘d1 = ‘, 0.0009999275207519531)
(‘d2 = ‘, 0.0009999275207519531)
(‘d3 = ‘, 0.0010001659393310547)
(‘d1 = ‘, 0.013000011444091797)
(‘d2 = ‘, 0.011999845504760742)
(‘d3 = ‘, 0.006000041961669922)
(‘d1 = ‘, 0.127000093460083)
(‘d2 = ‘, 0.11800003051757812)
(‘d3 = ‘, 0.06399989128112793)
dictionary value equal True True True
——————————“`
消耗时间的长短测试
方法以及代码
#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
——————————“`
相关文章推荐
- sql 一对多 出一条结果及两列选择一个的方法,null值设置默认值
- 本方法只需要设置一个GridView的宽度,其它宽度不需要设置。测试环境:IE6,Firefox通过。
- 设置元素的高度为百分比,结果不起作用的解决方法
- [原创]MongoDB、HandlerSocket和MySQL性能测试及其结果分析
- 安装MANTIS测试环境后,解决页面显示警告时区设置不正常的方法
- ASP.NET里,URL重写的方法设置伪静态(测试成功)
- 关于异步事件的一个测试及其分析结果
- DedeAMPZ创建多个站点本地测试的设置方法
- Watir自动测试应用(2):Watir安装及其环境设置
- LoadRunner测试中遇见的不可思议的问题及其解决方法
- MongoDB、HandlerSocket和MySQL性能测试及其结果分析
- 关于RDA的Push和Pull方法多种情况的测试结果
- CETK测试原理/测试方法/测试结果分析以及常见WinCE Test Kit运行问题的排查
- 比较全面DataRow的映射的helper,兼测lambda方式的快速SetValue方法(测试结果大大出乎意料)
- Domino Web引擎最大搜索结果数设置方法
- C++类及其实例所占据空间(自己测试结果)
- 光纤损耗测试方法及其注意事项 推荐
- agsXMPP客户端关于好友在线状态的设置及其响应的方法
- MongoDB、HandlerSocket和MySQL性能测试及其结果分析
- ASP.NET里,URL重写的方法设置伪静态(测试成功)