Ticket #1007: slowleak.py

File slowleak.py, 2.1 KB (added by Greg Couch, 8 years ago)
Line 
1import gc
2import sys
3from chimerax.core.commands import open, close
4from chimerax.core.atomic import AtomicStructure
5
6# PDB_ID = '2hmg' # large protein
7PDB_ID = '3rec' # smallest PDB file
8# PDB_ID = 'water.cif' # just waters
9
10
11def gc_histogram():
12 """Returns per-class counts of existing objects."""
13 result = {}
14 for o in gc.get_objects():
15 t = type(o)
16 count = result.get(t, 0)
17 result[t] = count + 1
18 return result
19
20
21def diff_hists(h1, h2):
22 """Prints differences between two results of gcHistogram()."""
23 for k in h2:
24 if k in h1:
25 continue
26 h1[k] = 0
27 for k in h1:
28 if k not in h2:
29 h2[k] = 0
30 if h1[k] != h2[k]:
31 print("%s: %d -> %d (%s%d)" % (
32 k, h1[k], h2[k], h2[k] > h1[k] and "+" or "",
33 h2[k] - h1[k]))
34
35
36# open/close once to populate caches
37models = open.open(session, PDB_ID)
38close.close(session, models)
39del models
40session.main_view.check_for_drawing_change()
41
42gc.collect()
43if 0:
44 gc.set_debug(gc.DEBUG_LEAK)
45else:
46 gc.set_debug(gc.DEBUG_SAVEALL)
47hist1 = gc_histogram()
48models = open.open(session, PDB_ID)
49for m in models:
50 print('After open:', m, sys.getrefcount(m))
51del m
52close.close(session, models)
53del models
54session.main_view.check_for_drawing_change()
55
56gc.collect()
57hist2 = gc_histogram()
58diff_hists(hist1, hist2)
59
60for o in gc.get_objects():
61 if isinstance(o, AtomicStructure):
62 break
63else:
64 print('No AtomicStructure references!!')
65 raise SystemExit(0)
66gc.collect()
67
68del hist1, hist2
69
70print(sys.getrefcount(o), 'references to an AtomicStructure')
71
72if 1:
73 referrers = gc.get_referrers(o)
74 refs = ['%r from %s' % (type(x), type(x).__module__) for x in referrers
75 if id(x) != id(globals())]
76 print(len(refs), 'referrers:', ', '.join(refs))
77
78if 0:
79 referents = gc.get_referents(o)
80 refs = ['%r from %s' % (type(x), type(x).__module__) for x in referents]
81 print(len(referents), 'referents', ', '.join(refs))
82
83if 0:
84 tmp = ["%r from %s" % (type(g), type(g).__module__) for g in gc.garbage]
85 print(len(gc.garbage), "items in garbage:", ', '.join(tmp))
86
87raise SystemExit(1)