【问题标题】:Possible memory leak in Python scriptPython 脚本中可能存在内存泄漏
【发布时间】:2022-12-17 09:06:51
【问题描述】:

我在一台新笔记本电脑上运行 python 脚本。该脚本以简单的方式打开文件 .fits 循环,绘制文件的一部分,从图中选择点,将输出保存在 .dat 文件中。

import numpy as np
from matplotlib import pyplot as plt
from astropy.io import fits,ascii
from glob import glob
import gc

list_files=np.sort(glob('*.fits')) ### around 90 objects 
list_ranges=ascii.read('ranges.dat')#### aroung 1000 objects
for i in range(len(list_files):
    output.open(list_files[i]+'.dat','w')
    with fits.open(list_files[i]) as single_file:
        x=single_file[0].data[0]
        y=single_file[0].data[1]
    for j in range(len(list_ranges)):
        x_single=x[((x<list_ranges[j]+3) & (x>list_ranges[j]-3))]
        y_single=y[((x<list_ranges[j]+3) & (x>list_ranges[j]-3))]
        fig, ax = plt.subplots(figsize=(18,8))
        ax.plot(x,y)
        pts = np.asarray(plt.ginput(2, timeout=-1))
        output.write('%.2f %.2f\n'%(pts[0,0],pts[1,0]))
        plt.close()
        del x_single,y_single,pts
        gc.collect()
    output.close()
    del single_file,x,y
    gc.collect()

现在,这种脚本以前在其他设备上运行良好,但现在在第一个设备中循环 3-4 次后,一切都崩溃了,有时脚本被杀死,有时终端会自行关闭。 我在脚本中插入 os.system('free -h') 以检查内存,它以:

               total        used        free      shared  buff/cache   available
Mem:            15Gi       2.6Gi       8.5Gi       754Mi       4.2Gi        11Gi
Swap:          2.0Gi          0B       2.0Gi

第三个对象之后,情况是这样的:

               total        used        free      shared  buff/cache   available
Mem:            15Gi       5.5Gi       175Mi       7.8Gi       9.7Gi       1.7Gi
Swap:          2.0Gi       3.0Mi       2.0Gi

最后,我一直推到它崩溃并用 dmegs 检查,这是响应:

[ 5783.416916] oom-kill:constraint=CONSTRAINT_NONE,nodemask=
(null),cpuset=/,mems_allowed=0,global_oom,task_memcg=/user.slice/user-1000.slice
/user@1000.service/app.slice/app-org.gnome.Terminal.slice/vte-spawn-94017a15-
e67f-4443-87c5-a39220aa3d9c.scope,task=python3,pid=9500,uid=1000
[ 5783.416977] Out of memory: Killed process 9500 (python3) total-vm:9479428kB, anon-
rss:4419828kB, file-rss:0kB, shmem-rss:2580kB, UID:1000 pgtables:14068kB oom_score_adj:0

提前致谢。

【问题讨论】:

  • 看起来你没有打电话给single_file.close()。我认为 del 可能会自动执行此操作,但也有可能不会。
  • 您是否能够发布实际输入,以便您有一个最小的可重现示例?
  • 我改变了打开和关闭 single_file 的方式,但没有任何改变。不幸的是我不能发布输入,它们仍然是私人数据。
  • 似乎内存问题与 ax.plot(x,y) 有关,您可以尝试在 plt.close() stament 之前添加 plt.clf() 并且应该可以解决问题。 (没有测试数据很难自己检查)

标签: python python-3.x memory-leaks out-of-memory


【解决方案1】:

plt.close() 之前使用plt.clf() 应该可以保持较低的内存使用率。

查看此类似问题以获取更多信息:Keep memory usage low

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-16
    • 2011-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-23
    相关资源
    最近更新 更多