Python: Ctypes如何检查内存管理

Python: Ctypes how to check memory management

所以我使用 Python 作为前端 GUI,它与一些 C 文件交互以作为后端进行存储和内存管理。每当 GUI 的 window 关闭或退出时,我都会为分配的变量调用所有析构函数方法。

在退出整个程序之前是否有检查内存泄漏或可用性的方法,例如 C Valgrind 检查,以确保没有任何内存泄漏?

退出示例:

from tkinter import *
root = Tk()  # New GUI
# some code here

def destructorMethods:
    myFunctions.destructorLinkedList()  # Destructor method of my allocated memory in my C file
    # Here is where I would want to run a Valgrind/Memory management check before closing
    root.destroy()  # close the program

root.protocol("WM_DELETE_WINDOW", destructorMethods)  # When the close window option is pressed call destructorMethods function

我认为您可以使用支持泄漏检测的调试内存分配器。

像 tcmalloc 这样的东西就可以了。您只需 LD_PRELOAD 它和您对 malloc 、 free 等的所有调用都将调试泄漏。

trace python memory leaks 查看这篇文章,并 - 有关这些问题的更多详细信息,请参见此处:

  • How to use valgrind with python?
  • Python memory leaks

如果您想使用 Valgrind,那么这个 readme might be helpful. Probably, this 可能是使 Valgrind 友好 python 并在您的程序中使用它的另一个好资源。

但是如果你考虑其他类似 tracemalloc 的东西,那么你可以很容易地获得它的一些示例用法 here。这些例子很容易解释。例如根据他们的文档,

  import tracemalloc
  tracemalloc.start()

  # ... run your application ...
  snapshot = tracemalloc.take_snapshot()
  top_stats = snapshot.statistics('lineno')
  print("[ Top 10 ]")
  for stat in top_stats[:10]:
  print(stat)

这将输出类似的内容。

 <frozen importlib._bootstrap>:716: size=4855 KiB, count=39328, average=126 B
 <frozen importlib._bootstrap>:284: size=521 KiB, count=3199, average=167 > 

您可以解析它以绘制内存使用情况以供您调查,也可以 使用参考 doc 以获得更具体的想法。

在这种情况下,您的程序可能如下所示:

 from tkinter import *
 import tracemalloc
 root = Tk()  # New GUI
 # some code here

 def destructorMethods:
     tracemalloc.start()
     myFunctions.destructorLinkedList()  # Destructor method of my allocated memory in my C file
     # Here is where I would want to run a Valgrind/Memory management check before closing
     snapshot = tracemalloc.take_snapshot()
     top_stats = snapshot.statistics('lineno')
     print("[ Top 10 ]")
     for stat in top_stats[:10]:
         print(stat)
     
     root.destroy()  # close the program

 root.protocol("WM_DELETE_WINDOW", destructorMethods)  

另一种选择是,您可以使用内存分析器查看不同时间的内存使用情况。该软件包可用 here。安装此软件包后,您可以在脚本中使用以下命令来获取 png 文件中随时间变化的内存使用情况。

 mprof run --include-children python your_filename.py
 mprof plot --output timelyplot.png

或者您可以根据需要使用 memory_profiler 包中提供的不同功能。也许 this 教程对您来说很有趣。