gpt4 book ai didi

performance - Python 3.3 在大循环期间变慢

转载 作者:行者123 更新时间:2023-12-04 05:00:55 25 4
gpt4 key购买 nike

我对编程还很陌生,不明白我的程序变慢的原因。

我正在处理大约 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

每个列表列表中的内部列表需要保持有序,所以我认为我不能使用集合。

以下两个问题非常相似,以至于我在提问之前尝试/考虑了他们的评论。

python function slowing down for no apparent reason

Python function slows down with presence of large list

最佳答案

好的,让我们使用 Python 3.3。
我想对于 oldListOfLists 中的每个列表应该是 newListOfLists 中的一个,并且您主要更新值,因此,例如,oldListOfLists 的第 0 个由 newListOfLists 的第 0 个更新,1ft 等等 - 相同的索引,您可以简化您的代码。

def updateOldList(oldListOfLists, newListOfLists):

for i in range(lenNewListOfLists):
try:
oldListOfLists[i][0] = newListOfLists[i][0]
oldListOfLists[i][3] = newListOfLists[i][3]
except IndexError:
oldListOfLists+=newListOfLists

return oldListOfLists

如果 oldListofLists 中的列表没有被 newListOfLists 中具有相同索引的列表更新,它实际上将无法正常工作,您可以想象一下。

编辑:您可能想要捕获类似 IndexError 的内容,以防事件新列表没有相应的旧列表,而其他的则没有,一般错误。

Edit2 : += 是扩展的别名。
oldListOfLists+=newListOfLists

是一样的
oldListOfLists.extend(newListOfLists)  

Edit3:代码仍然变慢吗?您的最后一个列表(在索引中)是否变得越来越大?
两个列表的总内存大小是多少?

关于performance - Python 3.3 在大循环期间变慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16155064/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com