【发布时间】:2013-04-22 19:22:22
【问题描述】:
我对编程还很陌生,不明白我的程序速度变慢的原因。
我正在处理大约 350,000 - 500,000 行的数据集,希望能得到一些指导。
我需要对照旧列表检查新列表中的所有条目,以便更新旧条目并将全新的条目添加到列表末尾。
如果将打印语句添加到重新分配循环并且新行异常,则最初的几千次迭代很快,但之后程序变得非常慢。 (在前 3 秒内完成了近 1000 个完整的循环,在大约第 20,000 次迭代之后,速度降低到低于 5 秒内的 100 个完整循环,到第 60,000 次迭代,它比 15 秒内的 100 个完整循环慢。)
RAM 的使用率低于 70%,而 CPU 一直保持在 48% 到 50% 之间
代码如下所示:
import gc
gc.disable() #this was added to possibly improve speed
def updateOldList(oldListOfLists, newListOfLists):
oldListIndexDict = dict()
IDNumber = <index of ID number>
for i in range(len(oldListOfLists)):
oldListIndexDict[oldList[i][IDNumber]] = i
for i in range(len(newListOfLists)):
try:
oldIndex = oldListIndexDict[newListOfLists[i][IDNumber]]
oldListOfLists[oldIndex][0] = newListOfLists[i][0]
oldListOfLists[oldIndex][3] = newListOfLists[i][3]
del(oldListIndexDict[newListOfLists[i][IDNumber]]) #this was added to limit the number of entries in the hash table to attempt to improve speed
except:
oldListOfLists= oldListOfLists + newListOfLists
return oldListOfLists
每个列表列表中的内部列表需要保持有序,所以我认为我不能使用集合。
以下两个问题非常相似,我在询问之前尝试/考虑了他们的 cmets。
【问题讨论】:
-
如果删除
gc.disable()会怎样?一样吗? -
我原来是这样的,加了小有收获。
-
不要使用空的 except: 子句,准确列出您想要捕获的内容以隐藏错误。乍一看,我担心的是您的 old = old+new 行在每次循环迭代时都会复制和销毁越来越大的列表。请改用 old.extend(new)。
-
这解决了这个问题。如果您重新提交此问题作为答案,我会将问题标记为已回答。谢谢
标签: performance list dictionary python-3.x