如何阻止Python程序不断增加内存使用率?

如何阻止Python程序不断增加内存使用率?,python,multithreading,ram,Python,Multithreading,Ram,我创建了一个小程序来测量我的4g数据消耗量,它运行得很好。。。 除了一部分 在运行了一整天之后,我听到我的计算机发出了前所未有的声音,当我去我的任务管理器时,我惊讶地受到了使用3GB内存的Python程序的欢迎。 我停止程序并重新运行它。它从20MB的内存消耗开始,并不断增加 我尝试使用垃圾收集器来(释放)每次返回的值,但这没有帮助,因为返回值是一个浮点值。我确实尝试将其转换为int,但没有成功 import time import threading from tkinter import *

我创建了一个小程序来测量我的4g数据消耗量,它运行得很好。。。 除了一部分

在运行了一整天之后,我听到我的计算机发出了前所未有的声音,当我去我的任务管理器时,我惊讶地受到了使用3GB内存的Python程序的欢迎。 我停止程序并重新运行它。它从20MB的内存消耗开始,并不断增加

我尝试使用垃圾收集器来(释放)每次返回的值,但这没有帮助,因为返回值是一个
浮点值。我确实尝试将其转换为
int
,但没有成功

import time
import threading
from tkinter import *
import psutil
import socket
import gc

def running_processes():
    for proc in psutil.process_iter():
        try:
            # Get process name & pid from process object.
            processName = proc.name()
            processID = proc.pid
            print(processName , ' ::: ', processID)
        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
            pass

def data(start_val):
    # Returns the data consumed while connected
    start_val = 0
    result = 0
    global timer

    while True:
        current_val = psutil.net_io_counters().bytes_sent + psutil.net_io_counters().bytes_recv
        result = current_val - start_val + result
        start_val = current_val
        timer = threading.Timer(1.0, data)
        timer.start()
        timer.cancel()
        return convert_to_mo(result)

def main():
    # Runs and displays data
    kiss = data(0)
    display_label['text'] = str(kiss) + ' || Mo Consumed '
    display_label.pack()
    app.after(5, main)
    #gc.collect(kiss)

def convert_to_mo(value):
    # 1 octet = 1 byte = 8 bits // 1024 bytes = 8192 bits = 1 kb;
    return value/1000000

app = Tk()
app.title("Data Consumption Monitor")
app.geometry('420x40')
app.configure(background = 'black')
frame = Frame(app)
display_label = Label(frame, font = 'montserrat 20', bg = 'black', fg = '#20C20E')
frame.pack(anchor=CENTER)
running_processes()
main()
app.mainloop()

您每秒更新标签200次。这真的有必要吗?在你的
while True:
中,在最后使用
时间。sleep(0.1)
我不是Python专家,所以答案可能很明显,但是为什么你写
while True:…
然后在循环体中放一个无条件的
返回值呢?@BryanOakley我把它减少到每秒1次,谢谢你的提示!尽管我这么做了,但随着时间的推移,该程序的RAM消耗量仍在增加。@JasarOrion它大幅降低了内存使用量,但随着时间的推移仍在增加