我尝试通过 ctypes 包装一些 C 代码。虽然,我的代码(附在下面)是有效的,memory_profiler表明它在某处发生内存泄漏。我试图包装的基本 C 结构在“image.h”中定义。它定义了一个图像对象,包含一个指向数据的指针、一个指针数组(此处未包含的各种其他函数需要)以及一些形状信息。
image.h:
#include <stdio.h>
#include <stdlib.h>
typedef struct image {
double * data; /*< The main pointer to the image data*/
i3_flt **row; /*< An array of pointers to each row of the image*/
unsigned long n; /*< The total number of pixels in the image*/
unsigned long nx; /*< The number of pixels per row (horizontal image dimensions)*/
unsigned long ny; /*< The number of pixels per column (vertical image dimensions)*/
} image;
通过 ctypes 包装此 C 结构的 python 代码包含在下面的“image_wrapper.py”中。 python 类 Image 实现了很多我没有在此处包含的方法。这个想法是有一个 python 对象,它和 numpy 数组一样方便使用。事实上,该类包含一个 numpy 数组作为属性 (self.array),它指向与 C 结构中的数据指针完全相同的内存位置。
image_wrapper.py:
import numpy
import ctypes as c
class Image(object):
def __init__(self, nx, ny):
self.nx = nx
self.ny = ny
self.n = nx * ny
self.shape = tuple((nx, ny))
self.array = numpy.zeros((nx, ny), order='C', dtype=c.c_double)
self._argtype = self._argtype_generator()
self._update_cstruct_from_array()
def _update_cstruct_from_array(self):
data_pointer = self.array.ctypes.data_as(c.POINTER(c.c_double))
ctypes_pointer = c.POINTER(c.c_double) * self.ny
row_pointers = ctypes_pointer(
*[self.array[i,:].ctypes.data_as(c.POINTER(c.c_double)) for i in range(self.ny)])
ctypes_pointer = c.POINTER(ctypes_pointer)
row_pointer = ctypes_pointer(row_pointers)
self._cstruct = c.pointer(self._argtype(data=data_pointer,
row=row_pointer,
n=self.n,
nx=self.nx,
ny=self.ny))
def _argtype_generator(self):
class _Argtype(c.Structure):
_fields_ = [("data", c.POINTER(c.c_double)),
("row", c.POINTER(c.POINTER(c.c_double) * self.ny)),
("n", c.c_ulong),
("nx", c.c_ulong),
("ny", c.c_ulong)]
return _Argtype
现在,用 memory_profiler 测试上面代码的内存消耗表明 Python 的垃圾收集器无法清理所有引用。这是我的测试代码,它在不同大小的循环中创建数量可变的类实例。
test_image_wrapper.py
import sys
import image_wrapper as img
import numpy as np
@profile
def main(argv):
image_size = 500
print 'Create 10 images\n'
for i in range(10):
x = img.Image(image_size, image_size)
del x
print 'Create 100 images\n'
for i in range(100):
x = img.Image(image_size, image_size)
del x
print 'Create 1000 images\n'
for i in range(1000):
x = img.Image(image_size, image_size)
del x
print 'Create 10000 images\n'
for i in range(10000):
x = img.Image(image_size, image_size)
del x
if __name__ == "__main__":
main(sys.argv)
@profile 告诉 memory_profiler 分析后续函数,这里是 main。通过在 test_image_wrapper.py 上运行带有 memory_profiler 的 python
python -m memory_profiler test_image_wrapper.py
产生以下输出:
Filename: test_image_wrapper.py
Line # Mem usage Increment Line Contents
================================================
49 @profile
50 def main(argv):
51 """
52 Script to test memory usage of image.py
53 16.898 MB 0.000 MB """
54 16.898 MB 0.000 MB image_size = 500
55
56 16.906 MB 0.008 MB print 'Create 10 images\n'
57 19.152 MB 2.246 MB for i in range(10):
58 19.152 MB 0.000 MB x = img.Image(image_size, image_size)
59 19.152 MB 0.000 MB del x
60
61 19.152 MB 0.000 MB print 'Create 100 images\n'
62 19.512 MB 0.359 MB for i in range(100):
63 19.516 MB 0.004 MB x = img.Image(image_size, image_size)
64 19.516 MB 0.000 MB del x
65
66 19.516 MB 0.000 MB print 'Create 1000 images\n'
67 25.324 MB 5.809 MB for i in range(1000):
68 25.328 MB 0.004 MB x = img.Image(image_size, image_size)
69 25.328 MB 0.000 MB del x
70
71 25.328 MB 0.000 MB print 'Create 10000 images\n'
72 83.543 MB 58.215 MB for i in range(10000):
73 83.543 MB 0.000 MB x = img.Image(image_size, image_size)
74 del x
Python 中 Image 类的每个实例似乎留下大约 5-6kB,在处理 10k 图像时总计约 58MB。对于单个对象来说,这似乎并不多,但由于我必须依靠一千万来运行,所以我很在意。似乎导致泄漏的行是 image_wrapper.py 中包含的以下内容。
self._cstruct = c.pointer(self._argtype(data=data_pointer,
row=row_pointer,
n=self.n,
nx=self.nx,
ny=self.ny))
如上所述,Python 的垃圾收集器似乎无法清理所有引用。我确实尝试实现自己的 del 函数,比如
def __del__(self):
del self._cstruct
del self
不幸的是,这似乎无法解决问题。在花了一天时间研究并尝试了几种内存调试器之后,我最后的选择似乎是 stackoverflow。非常感谢您的宝贵意见和建议。
最佳答案
这可能不是唯一的问题,但可以肯定的是,字典 _ctypes._pointer_type_cache
中每个 _Argtype
: LP__Argtype
对的缓存是不是微不足道的。如果您清除
缓存,内存使用率应该会下降。
可以使用ctypes._reset_cache()
清除指针和函数类型缓存。请记住,清除缓存可能会导致问题。例如:
from ctypes import *
import ctypes
c_double_p = POINTER(c_double)
c_double_pp = POINTER(c_double_p)
class Image(Structure):
_fields_ = [('row', c_double_pp)]
ctypes._reset_cache()
nc_double_p = POINTER(c_double)
nc_double_pp = POINTER(nc_double_p)
旧指针仍然适用于 Image
:
>>> img = Image((c_double_p * 10)())
>>> img = Image(c_double_pp(c_double_p(c_double())))
重置缓存后创建的新指针将不起作用:
>>> img = Image((nc_double_p * 10)())
TypeError: incompatible types, LP_c_double_Array_10 instance
instead of LP_LP_c_double instance
>>> img = Image(nc_double_pp(nc_double_p(c_double())))
TypeError: incompatible types, LP_LP_c_double instance
instead of LP_LP_c_double instance
如果重置缓存可以解决您的问题,也许就足够了。但通常指针缓存既是必要的又是有益的,所以我个人会寻找另一种方式。例如,据我所知,没有理由为每个图像自定义 _Argtype
。您可以将 row
定义为初始化为指针数组的 double **
。
关于python - python 类中使用的 ctypes 指针导致的内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17125978/