not*_*ame 9 c python ctypes valgrind memory-management
所以我使用 Python 作为前端 GUI,它与一些 C 文件交互以作为后端进行存储和内存管理。每当 GUI 的窗口关闭或退出时,我都会为分配的变量调用所有析构函数方法。
无论如何,在退出整个程序以确保没有任何内存泄漏之前,是否可以检查内存泄漏或可用性,例如 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
Run Code Online (Sandbox Code Playgroud)
如果您想使用Valgrind,那么本自述文件可能会有所帮助。也许,这可能是另一个制作Valgrind友好的 python 并在程序中使用它的好资源。
但如果您考虑其他类似的事情,那么您可以在这里tracemalloc轻松获得它的一些示例用法。这些例子很容易解释。例如根据他们的文档,
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)
Run Code Online (Sandbox Code Playgroud)
这将输出类似的内容。
<frozen importlib._bootstrap>:716: size=4855 KiB, count=39328, average=126 B
<frozen importlib._bootstrap>:284: size=521 KiB, count=3199, average=167 >
Run Code Online (Sandbox Code Playgroud)
您可以解析它以绘制调查的内存使用情况,也可以使用参考文档来获得更具体的想法。
在这种情况下,您的程序可能类似于以下内容:
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)
Run Code Online (Sandbox Code Playgroud)
另一种选择是,您可以使用内存分析器来查看不同时间的内存使用情况。该软件包可在此处获取。安装此软件包后,您可以在脚本中使用以下命令来获取 png 文件中一段时间内的内存使用情况。
mprof run --include-children python your_filename.py
mprof plot --output timelyplot.png
Run Code Online (Sandbox Code Playgroud)
memory_profiler或者您可以根据需要使用包中提供的不同功能。也许本教程对您来说会很有趣。