class StatisticDiff: """ Statistic difference on memory allocations between an old and a new Snapshot instance. """ __slots__ = ('traceback', 'size', 'size_diff', 'count', 'count_diff')
def _compare_grouped_stats(old_group, new_group): statistics = [] for traceback, stat in new_group.items(): previous = old_group.pop(traceback, None) if previous is not None: stat = StatisticDiff(traceback, stat.size, stat.size - previous.size, stat.count, stat.count - previous.count) else: stat = StatisticDiff(traceback, stat.size, stat.size, stat.count, stat.count) statistics.append(stat)
for traceback, stat in old_group.items(): stat = StatisticDiff(traceback, 0, -stat.size, 0, -stat.count) statistics.append(stat) return statistics
@total_ordering class Frame: """ Frame of a traceback. """ __slots__ = ("_frame",)
def __init__(self, frame): # frame is a tuple: (filename: str, lineno: int) self._frame = frame
@total_ordering class Traceback(Sequence): """ Sequence of Frame instances sorted from the most recent frame to the oldest frame. """ __slots__ = ("_frames",)
def __init__(self, frames): Sequence.__init__(self) # frames is a tuple of frame tuples: see Frame constructor for the # format of a frame tuple self._frames = frames
def __len__(self): return len(self._frames)
def __getitem__(self, index): if isinstance(index, slice): return tuple(Frame(trace) for trace in self._frames[index]) else: return Frame(self._frames[index])
def __contains__(self, frame): return frame._frame in self._frames
def format(self, limit=None): lines = [] if limit is not None and limit < 0: return lines for frame in self[:limit]: lines.append(' File "%s", line %s' % (frame.filename, frame.lineno)) line = linecache.getline(frame.filename, frame.lineno).strip() if line: lines.append(' %s' % line) return lines
def get_object_traceback(obj): """ Get the traceback where the Python object *obj* was allocated. Return a Traceback instance.
Return None if the tracemalloc module is not tracing memory allocations or did not trace the allocation of the object. """ frames = _get_object_traceback(obj) if frames is not None: return Traceback(frames) else: return None
class Trace: """ Trace of a memory block. """ __slots__ = ("_trace",)
def __init__(self, trace): # trace is a tuple: (domain: int, size: int, traceback: tuple). # See Traceback constructor for the format of the traceback tuple. self._trace = trace
class _Traces(Sequence): def __init__(self, traces): Sequence.__init__(self) # traces is a tuple of trace tuples: see Trace constructor self._traces = traces
def __len__(self): return len(self._traces)
def __getitem__(self, index): if isinstance(index, slice): return tuple(Trace(trace) for trace in self._traces[index]) else: return Trace(self._traces[index])
def __contains__(self, trace): return trace._trace in self._traces
def _match_traceback(self, traceback): if self.all_frames: if any(self._match_frame_impl(filename, lineno) for filename, lineno in traceback): return self.inclusive else: return (not self.inclusive) else: filename, lineno = traceback[0] return self._match_frame(filename, lineno)
def _match(self, trace): domain, size, traceback = trace res = self._match_traceback(traceback) if self.domain is not None: if self.inclusive: return res and (domain == self.domain) else: return res or (domain != self.domain) return res
class DomainFilter(BaseFilter): def __init__(self, inclusive, domain): super().__init__(inclusive) self._domain = domain
class Snapshot: """ Snapshot of traces of memory blocks allocated by Python. """
def __init__(self, traces, traceback_limit): # traces is a tuple of trace tuples: see _Traces constructor for # the exact format self.traces = _Traces(traces) self.traceback_limit = traceback_limit
def dump(self, filename): """ Write the snapshot into a file. """ with open(filename, "wb") as fp: pickle.dump(self, fp, pickle.HIGHEST_PROTOCOL)
@staticmethod def load(filename): """ Load a snapshot from a file. """ with open(filename, "rb") as fp: return pickle.load(fp)
def _filter_trace(self, include_filters, exclude_filters, trace): if include_filters: if not any(trace_filter._match(trace) for trace_filter in include_filters): return False if exclude_filters: if any(not trace_filter._match(trace) for trace_filter in exclude_filters): return False return True
def filter_traces(self, filters): """ Create a new Snapshot instance with a filtered traces sequence, filters is a list of Filter or DomainFilter instances. If filters is an empty list, return a new Snapshot instance with a copy of the traces. """ if not isinstance(filters, Iterable): raise TypeError("filters must be a list of filters, not %s" % type(filters).__name__) if filters: include_filters = [] exclude_filters = [] for trace_filter in filters: if trace_filter.inclusive: include_filters.append(trace_filter) else: exclude_filters.append(trace_filter) new_traces = [trace for trace in self.traces._traces if self._filter_trace(include_filters, exclude_filters, trace)] else: new_traces = self.traces._traces.copy() return Snapshot(new_traces, self.traceback_limit)
def _group_by(self, key_type, cumulative): if key_type not in ('traceback', 'filename', 'lineno'): raise ValueError("unknown key_type: %r" % (key_type,)) if cumulative and key_type not in ('lineno', 'filename'): raise ValueError("cumulative mode cannot by used " "with key type %r" % key_type)
def statistics(self, key_type, cumulative=False): """ Group statistics by key_type. Return a sorted list of Statistic instances. """ grouped = self._group_by(key_type, cumulative) statistics = list(grouped.values()) statistics.sort(reverse=True, key=Statistic._sort_key) return statistics
def compare_to(self, old_snapshot, key_type, cumulative=False): """ Compute the differences with an old snapshot old_snapshot. Get statistics as a sorted list of StatisticDiff instances, grouped by group_by. """ new_group = self._group_by(key_type, cumulative) old_group = old_snapshot._group_by(key_type, cumulative) statistics = _compare_grouped_stats(old_group, new_group) statistics.sort(reverse=True, key=StatisticDiff._sort_key) return statistics
def take_snapshot(): """ Take a snapshot of traces of memory blocks allocated by Python. """ if not is_tracing(): raise RuntimeError("the tracemalloc module must be tracing memory " "allocations to take a snapshot") traces = _get_traces() traceback_limit = get_traceback_limit() return Snapshot(traces, traceback_limit)