Skip to content

Instantly share code, notes, and snippets.

@PolarNick239
Last active April 22, 2019 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PolarNick239/b611f85f590287dffb2ba6fa50089cc7 to your computer and use it in GitHub Desktop.
Save PolarNick239/b611f85f590287dffb2ba6fa50089cc7 to your computer and use it in GitHub Desktop.
import os
import time
def get_memory(key="total"):
key_to_index = {
"total": 1,
"used": 2,
"free": 3,
"shared": 4,
"buff/cache": 5,
"available": 6,
}
if key.startswith("swap"):
totalMemory = os.popen("free -m").readlines()[2].split()[key_to_index[key[4:]]]
else:
totalMemory = os.popen("free -m").readlines()[1].split()[key_to_index[key]]
return int(totalMemory)
def get_pids(appname):
pids = os.popen("pidof {}".format(appname)).readlines()
if len(pids) == 0:
return None
pids = pids[0].split()
return pids
def get_process_memory(pids, key="resident"):
if pids is None:
return 0
# See https://askubuntu.com/a/392274/859660
key_to_index = {
"size": 0,
"resident": 1,
"share": 2,
"trs": 3,
"drs": 4,
"lrs": 5,
"dt": 6,
}
total = 0
for pid in pids:
lines = os.popen("cat /proc/{}/statm".format(pid)).readlines()
if len(lines) == 1:
result = int(lines[0].split()[key_to_index[key]])
if key in {"size", "resident", "trs", "lrs", "share"}:
result = result * 4096 // 1024 // 1024 # Mb
elif key in {"drs", "dt"}:
pass
else:
result = 0
total += result
return total
if __name__ == '__main__':
delay_seconds = 1
appname = "metashape"
pids = get_pids(appname)
if pids is not None:
for pid in pids:
print("{} PID={} resident memory: {} Mb".format(appname, pid, get_process_memory([pid])))
else:
print("Failed to establish PID for {}".format(appname))
line_format = "[{: <20}, {: <20}, {: <20}, {: <20}, {: <20}, {: <20}, {: <20}, {: <20}, {: <20}, {: <20}, {: <20}],"
print(line_format.format("[Time, hh:mm:ss]", "[Total memory, Mb]", "[Used memory, Mb]", "[Free memory, Mb]", "[Shared memory, Mb]", "[Buff/cache, Mb]", "[Avail, Mb]", "[MS size, Mb]", "[MS resident, Mb]", "[MS share, Mb]", "[MS PIDs]", ))
while True:
cur_time = time.strftime("%H:%M:%S", time.localtime())
pids = get_pids(appname)
print(line_format.format(cur_time, get_memory("total"), get_memory("used"), get_memory("free"), get_memory("shared"), get_memory("buff/cache"), get_memory("available"), get_process_memory(pids, "size"), get_process_memory(pids, "resident"), get_process_memory(pids, "share"), str(pids) if pids is not None else "None"))
time.sleep(delay_seconds)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment