是什么导致我使用kivy的代码内存泄漏?

2024-05-04 10:05:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我在为标题烦恼。我在下面展示了根据代码结构我的代码缩短。代码假定保存为文件名“Revivation_memory_泄漏.py". 内存泄漏发生在命令return Rectangle(size=...)等处,由tracemalloc模块发现。有什么提示可以释放实例生成的矩形类的内存吗?在

from kivy.uix.widget import Widget
from kivy.graphics import Color, Line, Rectangle
import tracemalloc
from kivy.app import App
from kivy.clock import Clock
from kivy.uix.boxlayout import BoxLayout
from kivy.config import Config

width = 400
height = 300
Config.set('graphics', 'width', str(width))
Config.set('graphics', 'height', str(height))


class MyClass(Widget):

    def __init__(self):
        super().__init__()
        self.cnt_of_loop = 0
        self.gid = "1111"  # Group ID
        self.step_width = 10
        self.pos_x = 0

    def start(self):
        # start loopmethod()
        Clock.schedule_interval(self.loop, 0.01)

    def get_rectangle(self):
        self.pos_x += self.step_width
        if self.pos_x >= width:
            self.pos_x = self.step_width
        # This method returns customized every time kivy.graphics.Rectangle class instance
        # The below code seems to cause one of memory leak
        return Rectangle(size=(10, 30), pos=(self.pos_x, height / 2), group=self.gid)  # generate a Rectangle instance with gid "1111"

    def update_canvas(self):
        self.canvas.remove_group(self.gid)  # clear all canvas items with gid:"1111"
        self.canvas.add(Color(1, 0, 1, self.gid))
        self.canvas.add(self.get_rectangle())  # add new canvas one more items

    def loop(self, dt):
        """ This method called repeatedly and infinity """

        self.update_canvas()
        """ Show difference between used memory and it at step 10"""
        if self.cnt_of_loop == 10:
            self.snapshot1 = tracemalloc.take_snapshot()
        if self.cnt_of_loop > 200:
            snapshot2 = tracemalloc.take_snapshot()
            top_stats = snapshot2.compare_to(self.snapshot1, 'lineno')

            print("[ Top 10 differences]")
            for stat in top_stats[:10]:
                print(stat)
        self.cnt_of_loop += 1


class MyApp(App):
    def build(self):
        # return MyClass()
        a = MyClass()
        a.start()
        return a


if __name__ == '__main__':
    tracemalloc.start()
    MyApp().run()
  • 结果:

    • 请注意写为“复兴记忆”的行_泄漏.py". 写在注意行的命令似乎增加了内存大小。以下两个“十大差异”显示了早期和后期的结果。例如,“复兴记忆”_泄漏。py:37“,表示文件恢复内存的第37行_泄漏.py,内存大小从179KiB增加到276KiB。为什么不释放记忆?我认为当调用remove_group方法时,会释放绘图对象(例如矩形)的内存。在
  • 内存消耗的“早期阶段”

^{pr2}$
  • 内存消耗的“后期”
^{3}$

Tags: of内存frompyposimportselfloop