5

我尝试通过 ctypes 包装一些 C 代码。尽管如此,我的代码(附在下面)是正常的,memory_profiler表明它在某处出现内存泄漏。我试图包装的基本 C 结构在“image.h”中定义。它定义了一个图像对象,包含一个指向数据的指针、一个指针数组(此处未包含的各种其他函数需要),以及一些形状信息。

图像.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。非常感谢您的宝贵意见和建议。

4

3 回答 3

3

这可能不是唯一的问题,但可以肯定的是,字典中每个_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为每个图像进行自定义。您可以只定义rowdouble **指针数组的初始化。

于 2013-06-16T21:50:07.163 回答
0

您正在_Argtype为每个 Image 对象创建一个类对象。将定义移动_Argtype到全局范围将解决此内存泄漏。

您可以通过将以下行附加到您的测试代码来确认这一点:

print len(c.Structure.__subclasses__())

编辑

正如@eryksun 所说,ctypes 将所有 POINTER 类缓存在一个字典中,您可以通过以下行来确认这一点:

print c._pointer_type_cache
于 2013-06-17T03:40:44.563 回答
0

我正在使用 Python 2.7.3 和 Numpy 版本 1.6.1。

我怀疑罪魁祸首是这条线......

self.array = numpy.zeros((nx, ny), order='C', dtype=c.c_double)

根据这张票,1.6 版中存在内存泄漏numpy.zeroes(),这显然已在 1.7 版中修复。

于 2013-06-15T17:32:07.830 回答