我有以下脚本来填充测试数据库。
#!/usr/bin/python
import random, sys, sqlite3
con = sqlite3.connect('test.db')
cur = con.cursor()
cur.execute("DROP TABLE IF EXISTS EXAMPLE")
cur.execute("CREATE TABLE EXAMPLE(FIRST TEXT, SECOND TEXT)")
for i in range(0, 99999999):
one = format(i, '08d')
two = "%0.8d" % random.randint(0,99999999)
cur.execute("INSERT INTO EXAMPLE VALUES(\'"+one+"\',\'"+two+"\')")
con.commit()
# to have some feedback of the progress
if i % 100000 == 0:
print (str(i))
con.close()
print ("done")
# wait in the script..
sys.stdin.readline()
现在,脚本在大约 2 分钟内占用了它可以使用的所有 RAM(当前在 3GB 的虚拟机中运行 - 占用约 2.8GB)(编辑:几秒钟内)并且从未达到如果 i % 100000 == 0:
。
如果我终止它并检查 test.db
文件,它有 3KB 大并且仅包含表,没有条目。
我需要时不时地关闭并重新打开连接吗?
最佳答案
正如我的评论所建议的,在返回包含许多元素的列表时,您应该考虑使用 irange
而不是 range
,特别是如果您只想使用该列表一次.
区别在于实现。 range
预先创建整个列表,并返回列表中的元素。
irange
每次只是创建并返回列表中的下一个元素,因此它不需要预先做太多工作。
据我所知,函数调用是可以互换的,因此只需将代码中的 range
替换为 irange
,您就会看到更少的 RAM 消耗。
也请检查这个问题:How is irange() any different from range() or xrange()?
编辑:
抱歉,我回答得有点快。使用 xrange
而不是我之前写的 irange
。
何时使用其中之一:Should you always favor xrange() over range()?
在 Python 3 中使用 range 或 xrange 并不重要的原因是,据我所知,因为 range 是作为 xrange 实现的。
关于python - 为什么我的测试 sqlite 数据库的 'filling' 占用了这么多 RAM 并且没有保存任何内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26016318/