相关疑难解决方法(0)

Cherrypy中的内存消耗

我在RESTful Web服务中使用Cherrypy,服务器返回XML(lxml用于创建XML).其中一些XML非常庞大.我注意到在处理了这样的请求(返回大型XML)之后,内存没有被释放.

所以,我已经隔离了一个问题并创建了一个非常简短的虚拟示例:

import cherrypy
from lxml import etree

class Server:
    @cherrypy.expose
    def index(self):
        foo = etree.Element('foo')
        for i in range(200000):
            bar = etree.SubElement(foo, 'bar')
            bar1 = etree.SubElement(bar, 'bar1')
            bar1.text = "this is bar1 text ({0})".format(i)
            bar2 = etree.SubElement(bar, 'bar2')
            bar2.text = "this is bar2 text ({0})".format(i)
            bar3 = etree.SubElement(bar, 'bar3')
            bar3.text = "this is bar3 text ({0})".format(i)
            bar4 = etree.SubElement(bar, 'bar4')
            bar4.text = "this is bar4 text ({0})".format(i)
            bar5 = etree.SubElement(bar, 'bar5')
            bar5.text = "this is bar5 text ({0})".format(i) …
Run Code Online (Sandbox Code Playgroud)

python memory lxml cherrypy consumption

5
推荐指数
1
解决办法
2130
查看次数

Python:垃圾收集失败了吗?

请考虑以下脚本:

l = [i for i in range(int(1e8))]
l = []
import gc
gc.collect()
# 0
gc.get_referrers(l)
# [{'__builtins__': <module '__builtin__' (built-in)>, 'l': [], '__package__': None, 'i': 99999999, 'gc': <module 'gc' (built-in)>, '__name__': '__main__', '__doc__': None}]
del l
gc.collect()
# 0
Run Code Online (Sandbox Code Playgroud)

关键是,在所有这些步骤之后,我的机器上的这个python进程的内存使用率大约是30%(Python 2.6.5,请求的更多细节?).这是top的输出的摘录:

 PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND  
5478 moooeeeep 20   0 2397m 2.3g 3428 S    0 29.8   0:09.15 ipython  
Run Code Online (Sandbox Code Playgroud)

RESP.ps aux:

moooeeeep 5478  1.0 29.7 2454720 2413516 pts/2 S+   12:39 …
Run Code Online (Sandbox Code Playgroud)

python garbage-collection

4
推荐指数
3
解决办法
4670
查看次数

Python垃圾收集器的问题?

我有一个简单的程序,它读取包含几百万行的大文件,解析每一行(numpy array)并转换为一个双精度数组(python array),然后写入一个hdf5 file.我重复这个循环多天.读完每个文件后,我删除所有对象并调用垃圾收集器.当我运行该程序时,第一天解析没有任何错误,但在第二天我得到MemoryError.我监视了我的程序的内存使用情况,在解析的第一天,内存使用量约为1.5 GB.第一天解析完成后,内存使用量将降至50 MB.现在当第二天开始,我尝试从我得到的文件中读取行MemoryError.以下是该计划的输出.

source file extracted at C:\rfadump\au\2012.08.07.txt
parsing started
current time: 2012-09-16 22:40:16.829000
500000 lines parsed
1000000 lines parsed
1500000 lines parsed
2000000 lines parsed
2500000 lines parsed
3000000 lines parsed
3500000 lines parsed
4000000 lines parsed
4500000 lines parsed
5000000 lines parsed
parsing done.
end time is 2012-09-16 23:34:19.931000
total time elapsed 0:54:03.102000
repacking file
done
> s:\users\aaj\projects\pythonhf\rfadumptohdf.py(132)generateFiles()
-> while single_date …
Run Code Online (Sandbox Code Playgroud)

python numpy h5py

4
推荐指数
1
解决办法
522
查看次数

Python:脚本中的内存问题

我写了一个脚本,我阅读了大约 400 万个点和 800.000 个图。该脚本剪辑每个图中的点并为每个图保存一个新的文本文件。

一段时间后,我的 PC 内存已满。我曾试图挖掘我的脚本,但在每个循环中for i in xrange(len(sr)):,每个对象都会被替换,并将剪切的点保存在一个新的 txt 文件中。

在这种情况下是否有一些策略可以使用以提高内存使用率而不降低性能(脚本已经很慢)?我是python的初学者,如果问题很简单,我很抱歉。

提前致谢

inFile ="C://04-las_clip_inside_area//prova//Ku_115_class_Notground_normalize.las"
poly ="C://04-las_clip_inside_area//prova//ku_115_plot_clip.shp"
chunkSize = None
MinPoints = 1

sf = shapefile.Reader(poly) #open shpfile
sr = sf.shapeRecords()
poly_filename, ext = path.splitext(poly)
inFile_filename = os.path.splitext(os.path.basename(inFile))[0]
pbar = ProgressBar(len(sr)) # set progressbar
if chunkSize == None:
    points = [(p.x,p.y) for p in lasfile.File(inFile,None,'r')]
    for i in xrange(len(sr)):
        pbar.update(i+1) # progressbar
        verts = np.array(sr[i].shape.points,float)
        record = sr[i].record[0]
        index = nonzero(points_inside_poly(points, verts))[0]
        if len(index) >= MinPoints: …
Run Code Online (Sandbox Code Playgroud)

python memory performance memory-management

4
推荐指数
1
解决办法
300
查看次数

python列表中的内存泄漏问题

身份列表包含大约57000 张图像的大数组。现在,我正在借助itertools.product(). 这将整个列表存储在内存中,这非常昂贵,并且我的系统在 4 分钟后挂起。

如何优化以下代码并避免节省内存?`

for i in range(0, len(idendities) - 1):
    for j in range(i + 1, len(idendities)):
        cross_product = itertools.product(samples_list[i], samples_list[j])
        cross_product = list(cross_product)

        for cross_sample in cross_product:
            negative = []
            negative.append(cross_sample[0])
            negative.append(cross_sample[1])
            negatives.append(negative)
            print(len(negatives))

negatives = pd.DataFrame(negatives, columns=["file_x", "file_y"])
negatives["decision"] = "No"

negatives = negatives.sample(positives.shape[0])
Run Code Online (Sandbox Code Playgroud)

内存9.30会越来越高,有一点系统已经完全挂了。

我还根据他的回答实现了以下答案并修改了代码。

for i in range(0, len(idendities) - 1):
    for j in range(i + 1, len(idendities)):
        for cross_sample in itertools.product(samples_list[i], samples_list[j]):
            negative = [cross_sample[0], cross_sample[1]]
            negatives.append(negative)
            print(len(negatives)) …
Run Code Online (Sandbox Code Playgroud)

python optimization product list python-itertools

4
推荐指数
1
解决办法
339
查看次数

Python 2.6 GC似乎可以清理对象,但不会释放内存

我有一个用python 2.6编写的程序,它创建了大量的短期实例(这是一个典型的生产者 - 消费者问题).我注意到top和pmap报告的内存使用情况似乎在创建这些实例时会增加,并且永远不会再次下降.我担心我使用的一些python模块可能会泄漏内存,所以我仔细隔离了代码中的问题.然后我开始尽可能简短地再现它.我想出了这个:

class LeaksMemory(list):
    timesDelCalled = 0

    def __del__(self):
        LeaksMemory.timesDelCalled +=1


def leakSomeMemory():
    l = []
    for i in range(0,500000):
        ml = LeaksMemory()
        ml.append(float(i))
        ml.append(float(i*2))
        ml.append(float(i*3))
        l.append(ml)

import gc
import os


leakSomeMemory()

print("__del__ was called " + str(LeaksMemory.timesDelCalled) + " times")
print(str(gc.collect())  +" objects collected")
print("__del__ was called " + str(LeaksMemory.timesDelCalled) + " times")
print(str(os.getpid()) + " : check memory usage with pmap or top")
Run Code Online (Sandbox Code Playgroud)

如果你用'python2.6 -i memoryleak.py'这样运行它会停止,你可以使用pmap -x PID来检查内存使用情况.我添加了del方法,以便我可以验证GC是否正在发生.它不在我的实际程序中,似乎没有任何功能差异.每次调用leakSomeMemory()都会增加此程序消耗的内存量.我担心我会犯一些简单的错误,并且引用被意外保留,但无法识别它.

python memory memory-leaks

3
推荐指数
1
解决办法
2801
查看次数

在 webdriver 中对 Firefox 和 Chrome 的内存消耗进行基准测试

我正在尝试最大限度地增加可以在我的计算机上运行脚本的浏览器数量。当我启动webdriver. 例如:

from selenium import webdriver
driver = webdriver.Chrome()
driver.get('www.yahoo.com')

# - or - #

from selenium import webdriver
driver = webdriver.Firefox()
driver.get('www.yahoo.com')
Run Code Online (Sandbox Code Playgroud)

python firefox selenium google-chrome

3
推荐指数
1
解决办法
1634
查看次数

强制Python释放对象以释放内存

我正在运行以下代码:

from myUtilities import myObject
for year in range(2006,2015):
    front = 'D:\\newFilings\\'
    back = '\\*\\dirTYPE\\*.sgml'
    path = front + str(year) + back
    sgmlFilings = glob.glob(path)
    for each in sgmlFilings:
        header = myObject(each)
        try:
            tagged = header.process_tagged('G:')
        except Exception as e:
            outref = open('D:\\ProblemFiles.txt','a')
            outref.write(each '\n')
            outref.close()
            print each
Run Code Online (Sandbox Code Playgroud)

如果我从重启开始,python的内存分配/消耗相当小.随着时间的推移,虽然它显着增加,并且最终在大约一天后我的可用内存很少(24GB安装[294 mb free 23960 cached])并且Python在Windows任务管理器列表中声称的内存为3GB.我正在观察在针对文件集合运行代码所需的三天内这种增加.

我的印象是,因为我正在做所有事情

tagged = header.process_tagged('G:')
Run Code Online (Sandbox Code Playgroud)

与每个循环相关联的内存将被释放并进行垃圾回收.

有什么我可以做的来强制释放这个记忆.虽然我还没有运行统计数据但我可以通过观察磁盘上的活动来判断该进程随着时间的推移而减慢(并且内存〜块变大)进展

编辑

我看了下面引用的问题,我不认为这些问题与我在另一个问题中理解的问题相同,即他们抓住对象(三角形列表)并需要整个列表进行计算.在每个循环中,我正在读取文件,执行文件的某些处理,然后将其写回磁盘.然后我正在阅读下一个文件...

关于可能的内存泄漏,我在myObject中使用LXML

注意,自从这个问题的第一次迭代以来,我添加了MyUtilities导入myObject的行.MyUtilities拥有可以完成所有任务的代码

关于发布myUtilities的代码 - 远离基本问题 - 我完成了标题并在标记每次迭代后标记了东西并将结果写入另一个驱动器,事实上是一个新格式化的驱动器.

我研究过使用多处理,但我没有因为一个模糊的想法,因为这是I/O密集型,我将竞争驱动器头 - 也许这是错误的,但因为每次迭代需要我写几百MB文件我认为我会竞争写入甚至读取时间.

更新 - 所以我在myObjectclass中有一个案例,其中打开了一个文件

myString = open(somefile).read()

我改变了

with open(somefile,'r') …

python memory

2
推荐指数
1
解决办法
8321
查看次数

是否需要删除以释放内存

我有以下代码,在其中我重新分配了几个GB的列表:

    res = self.dict_cursor.fetchall()
    res_with_offers = []

    # we add in HDBUY, SDBUY for now -- HARDCODED
    for item in res:
        for avail_code in ['HDBUY', 'SDBUY']:
            _item = deepcopy(item)
            _item['avail_code'] = avail_code
            res_with_offers.append(_item)

    del res; # <== is this line needed?
    res = res_with_offers
Run Code Online (Sandbox Code Playgroud)

我的理解是del res;,作为下一行中的变量重新分配,它将删除res内存中的初始项。它是否正确?为什么或者为什么不?

python python-3.x

2
推荐指数
1
解决办法
150
查看次数