码迷,mamicode.com
首页 > 编程语言 > 详细

Python学习笔记_字典(Dict)_遍历_不同方法_性能测试对比

时间:2015-01-06 17:48:14      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:

今天专门把python的字典各种方法对比测试了一下性能效果.

 

测试代码如下:

 1 def dict_traverse():
 2     from time import clock
 3     my_dict = {name: Jim, age: 20, height: 180cm, weight: 60kg}
 4 
 5     t_start = clock()
 6     for key in my_dict:    # 性能最差写法.无优化
 7         print Type01.01: %s --- %s % (key, my_dict[key])
 8     t1 = clock()
 9 
10     for key in my_dict:    # 性能较上优,可见get()方法作了优化.
11         print Type01.02: %s --- %s % (key, my_dict.get(key))
12     t2 = clock()
13 
14     for key in my_dict.keys():    # keys()方法也是作了优化.
15         print Type02.01: %s --- %s % (key, my_dict[key])
16     t3 = clock()
17 
18     for key in my_dict.keys():    # 
19         print Type02.02: %s --- %s % (key, my_dict.get(key))
20     t4 = clock()
21 
22     for key, value in my_dict.items():   # 标准写法,性能最佳写法
23         print Type03: %s --- %s % (key, value)
24     t5 = clock()
25 
26     for key, value in my_dict.iteritems():    # 性能较上,有少量损失.
27         print Type04: %s --- %s % (key, value)
28     t6 = clock()
29 
30     for key, value in zip(my_dict.iterkeys(),my_dict.itervalues()):    # 性能较差.
31         print Type05: %s --- %s % (key, value)
32     t7 = clock()
33 
34     print ********** time cost ******************
35     print Type01.01 -- total time : , t1-t_start
36     print Type01.02 -- total time : , t2-t1
37     print Type02.01 -- total time : , t3-t2
38     print Type02.02 -- total time : , t4-t3
39     print Type03 -- total time : , t5-t4
40     print Type04 -- total time : , t6-t5
41     print Type05 -- total time : , t7-t6
42 
43 
44 
45 if __name__ == __main__:
46     dict_traverse()

 

经过多次运行,可发现不同写法,耗时是有差异.

对比结果如下图所示.  

技术分享

 

综上对比可发现:

对于字典遍历,推荐如下写法,性能最优.

1 for k, v in my_dict.items():
2     print k, v 

 

Python学习笔记_字典(Dict)_遍历_不同方法_性能测试对比

标签:

原文地址:http://www.cnblogs.com/selfrebuild/p/4206367.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!