mem.py 891 B

123456789101112131415161718192021222324252627282930
  1. # coding=utf-8
  2. import os
  3. import gc
  4. import threading
  5. from maxkb.const import CONFIG
  6. from common.utils.logger import maxkb_logger
  7. import random
  8. import psutil
  9. CURRENT_PID=os.getpid()
  10. # 1 hour
  11. GC_INTERVAL = 3600
  12. def enable_force_gc():
  13. before = int(psutil.Process(CURRENT_PID).memory_info().rss / 1024 / 1024)
  14. collected = gc.collect()
  15. try:
  16. import ctypes
  17. ctypes.CDLL("libc.so.6").malloc_trim(0)
  18. except Exception:
  19. pass
  20. after = int(psutil.Process(CURRENT_PID).memory_info().rss / 1024 / 1024)
  21. maxkb_logger.debug(f"(PID: {CURRENT_PID}) Forced GC ({collected} objects and {before - after} MB recycled)")
  22. t = threading.Timer(GC_INTERVAL - random.randint(0, 900), enable_force_gc)
  23. t.daemon = True
  24. t.start()
  25. if CONFIG.get("ENABLE_FORCE_GC", '1') == "1":
  26. maxkb_logger.info(f"(PID: {CURRENT_PID}) Forced GC enabled")
  27. enable_force_gc()