我尝试通过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的pythonpython -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。非常感谢您宝贵的意见和建议。
答案 0 :(得分:2)
这可能不是唯一的问题,但确保在dict _Argtype
中每个LP__Argtype
:_ctypes._pointer_type_cache
对的缓存并非无关紧要。如果clear
缓存,内存使用量应该会下降。
可以使用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 **
。
答案 1 :(得分:0)
我正在使用Python 2.7.3和Numpy版本1.6.1。
我怀疑罪魁祸首就是这条线......
self.array = numpy.zeros((nx, ny), order='C', dtype=c.c_double)
根据this ticket,版本1.6中的numpy.zeroes()
中存在内存泄漏,显然已在1.7版中修复。
答案 2 :(得分:0)
您正在为每个Image对象创建一个_Argtype
类对象。将_Argtype
的定义移动到全局范围将解决此内存泄漏。
您可以通过在测试代码中附加以下行来确认:
print len(c.Structure.__subclasses__())
修改强>
因为@eryksun说ctypes在一个字典中缓存所有POINTER类,你可以通过以下行确认:
print c._pointer_type_cache