Skip to content

Instantly share code, notes, and snippets.

@addam
Last active July 7, 2023 08:40
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 addam/36d1ca0e7613ea3418ed909610719251 to your computer and use it in GitHub Desktop.
Save addam/36d1ca0e7613ea3418ed909610719251 to your computer and use it in GitHub Desktop.
Record Docker memory usage in CSV format
import subprocess
import time
from sys import argv
run_args = "docker stats --format {{.MemUsage}}".split()
if len(argv) > 1:
run_args.append(argv[1])
background = subprocess.Popen(run_args, stdout=subprocess.PIPE)
units = {'Ki': 1e3, 'Mi': 1e6, 'Gi': 1e9, 'Ti': 1e12}
print("timestamp_seconds", "memory_bytes", flush=True)
start, now = None, 0
while True:
output = background.stdout.readline()
if output == "" and start is not None:
# exit when the container is done
break
if output:
output = output.decode("utf-8").split(" /")[0].strip()
if len(output) > 50:
# there is some garbage in the first output
continue
number = float(output[7:-3]) * units.get(output[-3:-1], 1)
if start is None:
start = time.time()
else:
now = time.time() - start
print(round(now), round(number), flush=True, sep=";")
time.sleep(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment