-
Notifications
You must be signed in to change notification settings - Fork 0
/
memory.py
47 lines (36 loc) · 1.16 KB
/
memory.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import logging
import os
import psutil
import sys
logger = logging.getLogger(__name__)
KB = 1024
MB = KB * KB
GB = 1024 * MB
TB = 1024 * GB
MEMORY_SIZES = [ "TB", "GB", "MB", "KB" ]
def toHuman(bytes):
for size in MEMORY_SIZES:
value = globals()[size]
if bytes >= value:
return f"{bytes / value:.1f}{size}"
return f"{bytes} bytes"
def usage(human=False):
process = psutil.Process(os.getpid())
memory = process.memory_info().rss
return toHuman(memory) if human else memory
def check(max, restart=True):
memory = usage()
# handle unfixable memory leak caused by rumps
if memory > max:
logger.info(f"Current memory usage is {toHuman(memory)}, which is larger than {toHuman(max)}.")
if restart:
os.execl(sys.executable, os.path.abspath(__file__), *sys.argv)
else:
logger.info(f"Current memory usage: {toHuman(memory)}, which is less than {toHuman(max)}.")
if __name__ == "__main__":
logger.info(toHuman(340))
logger.info(toHuman(2.5*KB))
logger.info(toHuman(2.5*MB))
logger.info(toHuman(2.5*GB + 2.5*MB))
logger.info(toHuman(2.5*TB))
check(GB, restart=False)