python – 循环性能下降
发布时间:2020-12-20 12:05:37 所属栏目:Python 来源:网络整理
导读:我有以下代码: keywordindex = cPickle.load(open('keywordindex.p','rb'))#contains~340 thousand itemsmasterIndex = {}indexes = [keywordindex]for partialIndex in indexes: start = time.time() for key in partialIndex.iterkeys(): if key not in m
我有以下代码:
keywordindex = cPickle.load(open('keywordindex.p','rb'))#contains~340 thousand items masterIndex = {} indexes = [keywordindex] for partialIndex in indexes: start = time.time() for key in partialIndex.iterkeys(): if key not in masterIndex.keys(): masterIndex[key]= partialIndex[key] elif key in masterIndex.keys(): masterIndex[key].extend(partialIndex[key]) cPickle.dump(masterIndex,open('MasterIndex.p','wb')) print int(time.time() - start),' seconds'#every thousand loops 并且我在循环运行时遇到性能下降,前10万次大约需要5秒钟,但每10万左右需要一秒钟,直到它花费3倍的时间.我试图以各种可能的方式简化代码,但我似乎无法弄清楚导致它的原因.是否有一个原因?这不是内存问题,我的使用率仅为30% 解决方法
这个块包含两个非常低效的编码实例:
if key not in masterIndex.keys(): masterIndex[key]= partialIndex[key] elif key in masterIndex.keys(): masterIndex[key].extend(partialIndex[key]) 首先,密钥在masterIndex中是否存在,因此对elif测试没有任何用处.如果未测试失败,则测试必须成功.所以这段代码也是这样的: if key not in masterIndex.keys(): masterIndex[key]= partialIndex[key] else: masterIndex[key].extend(partialIndex[key]) 其次,masterIndex是一个词典. Dicts支持非常有效的成员资格测试,无需你的任何帮助;-)通过将其密钥实现到一个列表(通过.keys()),你正在改变应该是一个快速的dict查找到一个可怕的慢速线性搜索列表.所以这样做: if key not in masterIndex: masterIndex[key]= partialIndex[key] else: masterIndex[key].extend(partialIndex[key]) 代码将运行得更快. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |