Skip to content

Instantly share code, notes, and snippets.

@sergey-miryanov
Last active March 18, 2026 15:00
Show Gist options
  • Select an option

  • Save sergey-miryanov/8fd2c7ad93d887f2ef81d7f292a1da0a to your computer and use it in GitHub Desktop.

Select an option

Save sergey-miryanov/8fd2c7ad93d887f2ef81d7f292a1da0a to your computer and use it in GitHub Desktop.
monitor.py
import gc
import json
import os
import sys
import _gc_monitor as m
import time
if len(sys.argv) == 2:
pid = int(sys.argv[-1])
else:
pid = os.getpid()
gc.collect()
print(F"self pid={os.getpid()}, target pid={pid}")
h = m.connect(pid)
print(h)
gens = {0:{}, 1:{}, 2:{}}
try:
while True:
items = h.read()
for item in items:
if item.ts > 0:
if item.ts not in gens[item.gen]:
print(F"gen={item.gen}, ts={item.ts:_}, duration={item.duration}s, total_duration={item.total_duration}s")
print(F" collections={item.collections}")
print(F" collected={item.collected:_}")
print(F" uncollectable={item.uncollectable:_}")
print(F" candidates={item.candidates:_}")
print(F" object_visits={item.object_visits:_}")
print(F" objects_transitively_reachable={item.objects_transitively_reachable:_}")
print(F" objects_not_transitively_reachable={item.objects_not_transitively_reachable:_}")
print(F" heap_size={item.heap_size:_}")
print(F" work_to_do={item.work_to_do:_}")
gens[item.gen][item.ts] = item
time.sleep(0.2)
except Exception as exc:
print(exc)
m.disconnect(h)
lines = []
for gen_idx, gen_items in gens.items():
for ts, item in gen_items.items():
ts = ts / 1e3
lines.append({
'name': F'gen_{gen_idx}',
'cat': F'gen_{gen_idx}',
'ph': 'C',
'ts': ts,
'args': {
'collected': item.collected,
'uncollectable': item.uncollectable,
'candidates': item.candidates,
'object_visits': item.object_visits,
'objects_transitively_reachable': item.objects_transitively_reachable,
'objects_not_transitively_reachable': item.objects_not_transitively_reachable,
'heap_size': item.heap_size,
'work_to_do': item.work_to_do,
}
})
lines.append({
'name': 'GC',
'ph': 'i',
'ts': ts,
's': 'p',
})
with open('..\\gc-trace.json', 'w') as f:
json.dump(lines, f)
f.flush()
f.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment