python性能对比之items
#1
#-*- coding:utf8-*- import datetime road_nodes = {} for i in range(5000000): road_nodes[i] = {'id':i} beg_time = datetime.datetime.now() for key, val in road_nodes.items(): pass end_time = datetime.datetime.now() print "time_scan:", end_time - beg_time
耗时
$python com_1.py time_scan: 0:00:17.126098
#2
#-*- coding:utf8-*- import datetime road_nodes = [] for i in range(5000000): road_nodes.append(i) beg_time = datetime.datetime.now() for key in road_nodes: pass end_time = datetime.datetime.now() print "time_scan:", end_time - beg_time
耗时
$python com_2.py time_scan: 0:00:00.325304
#3
#-*- coding:utf8-*- import datetime road_nodes = {} for i in range(5000000): road_nodes[i] = {'id':i} beg_time = datetime.datetime.now() for key in road_nodes: pass end_time = datetime.datetime.now() print "time_scan:", end_time - beg_time
耗时
$python com_3.py time_scan: 0:00:00.359197
总结
只对于字典key的遍历,用for key in dic方式
python性能对比之in list/dict
#1
from datetime import datetime a = [] for i in range(50000): a.append(i) aim_list = [] for i in range(1000000): aim_list.append(i) beg_time = datetime.now() for key in a: if key in aim_list: pass end_time = datetime.now() print "scan:", end_time - beg_time
运行
$python draw.py scan: 0:00:38.624985
#2
from datetime import datetime a = [] for i in range(50000): a.append(i) aim_list = {} for i in range(1000000): aim_list[i] = None beg_time = datetime.now() for key in a: if key in aim_list: pass end_time = datetime.now() print "scan:", end_time - beg_time
运行
$python draw2.py scan: 0:00:00.014031
分析
巨大的差异由 aim_list类型导致,一个是list,一个是dict
for i in ***时,list是一个个遍历,效率是O(n);dict是直接找到,效率是O(1)。