Python会吃掉我所有的交换记忆

2024-04-19 12:08:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个表上执行一个查询,在这个表中我得到一个列,其中有大约一亿行,这是因为我想用直方图来绘制它们。问题是,在程序退出之前,它几乎占用了我所有的内存(7.8gb)和交换内存(8gb),退出代码是-9当前fetchall()已完成。你知道吗

我怎样才能防止这种情况发生?我应该先对我的列进行排序,然后对其中的一些列进行几次查询,还是有更好的方法来获取查询中的数据?这个当前执行它本身几乎不需要时间。你知道吗

#!/usr/bin/python

import sqlite3 as lite
import numpy as np
import sys
import os
import matplotlib.pyplot as plt


def getQuantity(databasepath):
    con = lite.connect(databasepath)
    binwidth = 1
    start = time.time()
    with con:
        cur = con.cursor()
        cur.execute('SELECT latitude FROM MessageType1')
        con.commit()
        latitudes = cur.fetchall() #Breakdown here
        latitudes = [x[0] for x in latitudes]
        plt.hist(latitudes, bins=range(int(min(latitudes)), int(max(latitudes)) + binwidth, binwidth))
        plt.title("Bucket size: " + str(binwidth))
        plt.ylabel("Number of message")
        plt.savefig('latlongstats'+'t'+str(time.strftime("%H:%M:%S")), format='png')

if __name__ == "__main__":

    getQuantity('database/database.db')

Tags: path内存importtimeaspltlitecon
1条回答
网友
1楼 · 发布于 2024-04-19 12:08:19

我发现如果我替换了以下内容:

    latitudes = cur.fetchall()
    print "fetched"
    latitudes = [x[0] for x in latitudes]

使用:

    while True:
        tmp = cur.fetchone()
        if tmp != None:
            latitudes.append(tmp[0])
        else:
            break

我得到了同样的结果,尽管这需要永远的时间,而且几乎只吃掉了我的内存(但不是我的交换)。你知道吗

相关问题 更多 >