使用mysql-python时大数据集内存泄漏
我在使用mysqldbapi时遇到了我认为是内存泄漏的问题使用mysql-python时大数据集内存泄漏,python,mysql,Python,Mysql,我在使用mysqldbapi时遇到了我认为是内存泄漏的问题 Line # Mem usage Increment Line Contents ================================================ 6 @profile 7 10.102 MB 0.000 MB def main(): 8 10.105 MB 0.004 M
Line # Mem usage Increment Line Contents
================================================
6 @profile
7 10.102 MB 0.000 MB def main():
8 10.105 MB 0.004 MB connection = MySQLdb.connect(host="localhost", db="mydb",
9 11.285 MB 1.180 MB user="notroot", passwd="Admin123", use_unicode=True)
10 11.285 MB 0.000 MB cursor = connection.cursor(cursorclass=MySQLdb.cursors.SSCursor)
11
12 11.289 MB 0.004 MB cursor.execute("select * from a big table;")
13
14 254.078 MB 242.789 MB results = [result for result in cursor]
15 251.672 MB -2.406 MB del results
16 251.672 MB 0.000 MB return
另外,当使用guppy
/hpy
探索堆时,我的大部分内存都被unicode对象、int和datetime对象占用(很可能是MySQLdb API返回的行)
我在Ubuntu12.04上使用Python2.7.3,mysql-Python==1.2.4
,并使用memory\u-profiler
进行分析
这是不是如中所述的实习
我是否遗漏了任何悬而未决的参考资料
编辑:我也关闭了光标和连接,但仍然得到了类似的结果
已解决:
脸掌。我在做一个列表,自然地把所有的东西都记住了。当正确使用迭代器(流式传输到文件或其他内容)时,它的内存使用情况良好
Line # Mem usage Increment Line Contents
================================================
16 @profile
17 10.055 MB 0.000 MB def main():
18 10.059 MB 0.004 MB connection = MySQLdb.connect(host="localhost", db="mydb",
19 11.242 MB 1.184 MB user="notroot", passwd="Admin123", use_unicode=True)
20 11.242 MB 0.000 MB cursor = connection.cursor(cursorclass=MySQLdb.cursors.SSCursor)
21
22 11.246 MB 0.004 MB cursor.execute("select * from big table")
23 11.246 MB 0.000 MB count = 0
24 30.887 MB 19.641 MB for result in cursor:
25 30.887 MB 0.000 MB count = count + 1
26 30.895 MB 0.008 MB cursor.close()
27 30.898 MB 0.004 MB connection.close()
28 30.898 MB 0.000 MB return
由OP解决。他的原始代码包含这行代码
results = [result for result in cursor]
此列表将整个结果存储在内存中,而不是根据需要从服务器中流式传输。OP用一个简单的
for result in cursor:
...
看到他的内存使用恢复正常。删除光标时会发生什么?关闭连接?这听起来像是缓存。提示:当简单的
列表(条形图)
可以使用时,不要使用[foo for foo in bar]
。此外,操作系统不会立即释放内存。内存仍然分配给Python,以防进程再次需要它,只有在其他地方需要时才会从进程中删除它。仅仅因为python释放内存并不意味着操作系统会立即回收内存。在循环中运行它最终会消耗掉所有内存吗?@AndreiComan不能保证内存会返回到操作系统,这样top/ps/memory\u profiler和其他工具会显示进程内存使用量的减少。分配的地址空间在进程中保留在一个“池”中。这通常是没有问题的,因为这是虚拟内存,操作系统最终会通过交换未使用的物理内存来解决问题。这也不是python特有的。如果在执行类似操作时内存不断增加,这可能表明存在问题,尽管找到问题的解决方案非常好!你能把它写下来作为一个实际的答案,这样它就不再被标记为开放的了吗?