-
Notifications
You must be signed in to change notification settings - Fork 64
/
debug.py
206 lines (160 loc) · 5.13 KB
/
debug.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
"""
ouuu
Debugging routines, can only be used when Kupfer is run from the Source
directory.
"""
import atexit
import gc
import sys
import inspect
import logging
logger = logging.getLogger(__name__)
def get_size(obj, seen=None):
"""Recursively finds size of objects in bytes
from/based on: https://github.com/bosswissam/pysize/
"""
try:
size = sys.getsizeof(obj)
except RecursionError:
return 0
if seen is None:
seen = set()
obj_id = id(obj)
if obj_id in seen:
return 0
# Important mark as seen *before* entering recursion to gracefully handle
# self-referential objects
seen.add(obj_id)
if hasattr(obj, "__dict__"):
for cls in obj.__class__.__mro__:
if "__dict__" in cls.__dict__:
d = cls.__dict__["__dict__"]
if inspect.isgetsetdescriptor(d) or inspect.ismemberdescriptor(
d
):
size += get_size(obj.__dict__, seen)
break
if isinstance(obj, dict):
size += sum((get_size(v, seen) for v in obj.values()))
size += sum((get_size(k, seen) for k in obj.keys()))
elif hasattr(obj, "__iter__") and not isinstance(
obj, (str, bytes, bytearray)
):
try:
size += sum((get_size(i, seen) for i in obj))
except TypeError:
logging.exception("Unable to get size of %r.", obj)
if hasattr(obj, "__slots__"): # can have __slots__ with __dict__
size += sum(
get_size(getattr(obj, s), seen)
for s in obj.__slots__
if hasattr(obj, s)
)
return size
def mem_stats():
print("DEBUG: OBJ STATS")
print("enabled:", gc.isenabled())
print("objs", len(gc.get_objects()))
print("collected (now)", gc.collect())
# after collection
hist = {}
for obj in gc.get_objects():
key = str(type(obj))
if key not in hist:
hist[key] = 1
else:
hist[key] += 1
best = list(hist.items())
best.sort(key=lambda x: x[1], reverse=True)
print("\n".join(f"{k}: {v}" for k, v in best[:10]))
our = []
gtk = []
for item in best:
if "objects." in item[0] or "kupfer." in item[0]:
our.append(item)
if "gtk" in item[0]:
gtk.append(item)
# print "---just gtk (top)"
# print "\n".join("%s: %d" % (k,v) for k,v in gtk[:10])
print("---Just our objects (all > 1)")
print("\n".join(f"{k}: {v}" for k, v in our if v > 1))
print("---------------------\n")
def make_histogram(vect, nbins=7):
"""make a histogram out of @vect"""
mi, ma = 0, max(vect)
bins = [0] * nbins
bin_size = ma / nbins + 1
def brange(i):
return range(i * bin_size, (i + 1) * bin_size)
for acc in vect:
for i in range(nbins):
if acc in brange(i):
bins[i] += 1
break
# headers
print(
" ".join(
"%10s" % ("[%2d, %2d)" % (min(brange(i)), max(brange(i))),)
for i in range(nbins)
)
)
print(" ".join("%10d" % bins[i] for i in range(nbins)))
print("---------------------\n")
def icon_stats():
from kupfer import icons
print("DEBUG: ICON STATS")
print("size:", len(icons._ICON_CACHE))
for size, key in icons._ICON_CACHE.keys():
print(" ", size, key)
print("---------------------\n")
def learn_stats():
from kupfer.core.learn import _REGISTER, _CORRELATION_KEY, _ACTIVATIONS_KEY
print("Learn _REGISTER:")
for k, v in _REGISTER.items():
if k not in (_CORRELATION_KEY, _ACTIVATIONS_KEY):
print(f" {k}: {v}")
if _CORRELATION_KEY in _REGISTER:
print("------")
print("Correlations:")
for k, v in _REGISTER[_CORRELATION_KEY].items(): # type: ignore
print(f" {k}: {v}")
if _ACTIVATIONS_KEY in _REGISTER:
print("------")
print("Activations:")
for k, v in _REGISTER[_ACTIVATIONS_KEY].items(): # type: ignore
print(f" {k}: {v}")
print("---------------------\n")
def cache_stats():
import gc
import functools
from kupfer.support.datatools import LruCache, simple_cache
print("Cache")
for obj in gc.get_objects():
if isinstance(obj, (LruCache, simple_cache)):
print(str(obj), get_size(obj))
print("\nfunctools.*cache")
for obj in gc.get_objects():
if isinstance(obj, functools._lru_cache_wrapper):
print(
obj.__wrapped__.__module__,
obj.__wrapped__.__name__,
obj.cache_info(),
get_size(obj),
)
print("---------------------\n")
def opened_files():
try:
import psutil
except ImportError:
return
print("Opened files")
for file in psutil.Process().open_files():
print(str(file))
print("---------------------\n")
def install():
"""Install atexit handlers for debug information"""
atexit.register(opened_files)
atexit.register(mem_stats)
atexit.register(icon_stats)
atexit.register(learn_stats)
atexit.register(cache_stats)