gpt4 book ai didi

python - netcdf4-python : memory increasing with numerous calls to slice data from netcdf object

转载 作者:太空狗 更新时间:2023-10-29 20:31:32 25 4
gpt4 key购买 nike

我正在尝试使用 netcdf4-python 从 netcdf4 文件中读取数据切片。这是第一次使用 python,我遇到了内存问题。下面是代码的简化版本。在循环的每次迭代中,内存跳转相当于我读取的数据片。如何在遍历每个变量时清理内存?

#!/usr/bin/env python
from netCDF4 import Dataset
import os
import sys
import psutil

process = psutil.Process(os.getpid())


def print_memory_usage():
nr_mbytes = process.get_memory_info()[0] / 1048576.0
sys.stdout.write("{}\n".format(nr_mbytes))
sys.stdout.flush()

# open input file and gather variable info

rootgrp_i = Dataset('data.nc','r')
vargrp_i = rootgrp_i.variables
# lets create a dictionary to store the metadata in
subdomain = {}
for suff in range(1000):

for var in vargrp_i:
v_i = vargrp_i[var]
if v_i.ndim == 1:
a=v_i[:]
elif v_i.ndim == 2:
a=v_i[0:20, 0:20]
elif v_i.ndim == 3:
a=v_i[0, 0:20, 0:20]
elif v_i.ndim == 4:
a=v_i[0, 0:75, 0:20, 0:20]
else:
a=v_i[0]
del a
print_memory_usage()

rootgrp_i.close()

最佳答案

我认为问题是对 del a 含义的误解。

根据 Python Language Reference :

Deletion of a name removes the binding of that name from the local or global namespace, depending on whether the name occurs in a global statement in the same code block.

这意味着 del a 取消引用 a 变量,但这并不意味着内存将立即释放,这取决于垃圾收集器的工作方式。您可以要求垃圾收集器使用 collect() 方法收集新垃圾:

import gc
gc.collect()

This相关帖子可能会有用。

关于python - netcdf4-python : memory increasing with numerous calls to slice data from netcdf object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19313529/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com