'Program Process uses much more RAM with Threads

Im currently working on a Assistant for my daily Tasks to automate them.

One of it is a Thread which waits until i press F12. Everything works fine the Problem is : if i repeat taking a screenshot with F12 for every Usage the Process gets bigger. Beginning like 24mb, after pressing it 10x times 600-700

from threading import Timer, Thread, Event
import keyboard
import pyautogui
from datetime import datetime

class ScreenshotThread(Thread):
    # Initialize MyThread
    def __init__(self):
        # Inherits from Thread
        Thread.__init__(self)
        # Instance of MyThread


    # The run Func with code that runs repeatedly
    def run(self):
        while True:
            keyboard.wait('f12')
            now = datetime.now()
            screenshot = pyautogui.screenshot()
            screenshot.save(f'C:\\Users\\K\\Pictures\\Screenshots\\ 
                            {now.strftime("%m_%d_%Y_%H_%M_%S")}.png')

if __name__ == '__main__':
    ScreenshotT = ScreenshotThread()

    # Start Threading
    
    ScreenshotT.start()
    #PGM CODE check_updates()
    #PGM CODE main_menu()

Why is it getting bigger and how i can handle it?



Solution 1:[1]

Welcome to the wonderful concept of garbage collection (sarcasm very much intended).

Memory management is handled by python itself using Garbage Collection. Normally you should not touch this at all. Garbage collection is automagic in python. Unless you actually have a good reason to mess with it, don't. Also note that garbage collection is very lazy in python. You really should not touch this with a ten-foot pole unless you really need to.

However, you can force garbage collection, which can be useful if you are dealing with a limited resource system fe. I will not repeat stuff that others have explained much better than me, but I suggest to start reading about it here.

Note that I do not understand why you're using a threaded implementation, as for the code that you provide that should not be needed, because there's only a single simple loop.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Edo Akse