blob: 9d1cb177d74e5a340eae1d5c829dd91859aa072f [file] [log] [blame]
Victor Stinnered3b0bc2013-11-23 12:27:24 +01001:mod:`tracemalloc` --- Trace memory allocations
2===============================================
3
4.. module:: tracemalloc
5 :synopsis: Trace memory allocations.
6
R David Murray6d5cb072013-12-20 14:48:50 -05007.. versionadded:: 3.4
8
Victor Stinnered3b0bc2013-11-23 12:27:24 +01009The tracemalloc module is a debug tool to trace memory blocks allocated by
10Python. It provides the following information:
11
12* Traceback where an object was allocated
13* Statistics on allocated memory blocks per filename and per line number:
14 total size, number and average size of allocated memory blocks
15* Compute the differences between two snapshots to detect memory leaks
16
17To trace most memory blocks allocated by Python, the module should be started
18as early as possible by setting the :envvar:`PYTHONTRACEMALLOC` environment
19variable to ``1``, or by using :option:`-X` ``tracemalloc`` command line
20option. The :func:`tracemalloc.start` function can be called at runtime to
21start tracing Python memory allocations.
22
23By default, a trace of an allocated memory block only stores the most recent
24frame (1 frame). To store 25 frames at startup: set the
25:envvar:`PYTHONTRACEMALLOC` environment variable to ``25``, or use the
Victor Stinner3728d6c2013-11-23 12:37:20 +010026:option:`-X` ``tracemalloc=25`` command line option.
Victor Stinnered3b0bc2013-11-23 12:27:24 +010027
Victor Stinnered3b0bc2013-11-23 12:27:24 +010028
29Examples
Georg Brandl717e0282014-10-31 10:21:07 +010030--------
Victor Stinnered3b0bc2013-11-23 12:27:24 +010031
32Display the top 10
Georg Brandl717e0282014-10-31 10:21:07 +010033^^^^^^^^^^^^^^^^^^
Victor Stinnered3b0bc2013-11-23 12:27:24 +010034
35Display the 10 files allocating the most memory::
36
37 import tracemalloc
38
39 tracemalloc.start()
40
41 # ... run your application ...
42
43 snapshot = tracemalloc.take_snapshot()
44 top_stats = snapshot.statistics('lineno')
45
46 print("[ Top 10 ]")
47 for stat in top_stats[:10]:
48 print(stat)
49
50
51Example of output of the Python test suite::
52
53 [ Top 10 ]
54 <frozen importlib._bootstrap>:716: size=4855 KiB, count=39328, average=126 B
55 <frozen importlib._bootstrap>:284: size=521 KiB, count=3199, average=167 B
56 /usr/lib/python3.4/collections/__init__.py:368: size=244 KiB, count=2315, average=108 B
57 /usr/lib/python3.4/unittest/case.py:381: size=185 KiB, count=779, average=243 B
58 /usr/lib/python3.4/unittest/case.py:402: size=154 KiB, count=378, average=416 B
59 /usr/lib/python3.4/abc.py:133: size=88.7 KiB, count=347, average=262 B
60 <frozen importlib._bootstrap>:1446: size=70.4 KiB, count=911, average=79 B
61 <frozen importlib._bootstrap>:1454: size=52.0 KiB, count=25, average=2131 B
62 <string>:5: size=49.7 KiB, count=148, average=344 B
63 /usr/lib/python3.4/sysconfig.py:411: size=48.0 KiB, count=1, average=48.0 KiB
64
65We can see that Python loaded ``4.8 MiB`` data (bytecode and constants) from
66modules and that the :mod:`collections` module allocated ``244 KiB`` to build
67:class:`~collections.namedtuple` types.
68
69See :meth:`Snapshot.statistics` for more options.
70
71
72Compute differences
Georg Brandl717e0282014-10-31 10:21:07 +010073^^^^^^^^^^^^^^^^^^^
Victor Stinnered3b0bc2013-11-23 12:27:24 +010074
75Take two snapshots and display the differences::
76
77 import tracemalloc
78 tracemalloc.start()
79 # ... start your application ...
80
81 snapshot1 = tracemalloc.take_snapshot()
82 # ... call the function leaking memory ...
83 snapshot2 = tracemalloc.take_snapshot()
84
85 top_stats = snapshot2.compare_to(snapshot1, 'lineno')
86
87 print("[ Top 10 differences ]")
88 for stat in top_stats[:10]:
89 print(stat)
90
91Example of output before/after running some tests of the Python test suite::
92
93 [ Top 10 differences ]
94 <frozen importlib._bootstrap>:716: size=8173 KiB (+4428 KiB), count=71332 (+39369), average=117 B
95 /usr/lib/python3.4/linecache.py:127: size=940 KiB (+940 KiB), count=8106 (+8106), average=119 B
96 /usr/lib/python3.4/unittest/case.py:571: size=298 KiB (+298 KiB), count=589 (+589), average=519 B
97 <frozen importlib._bootstrap>:284: size=1005 KiB (+166 KiB), count=7423 (+1526), average=139 B
98 /usr/lib/python3.4/mimetypes.py:217: size=112 KiB (+112 KiB), count=1334 (+1334), average=86 B
99 /usr/lib/python3.4/http/server.py:848: size=96.0 KiB (+96.0 KiB), count=1 (+1), average=96.0 KiB
100 /usr/lib/python3.4/inspect.py:1465: size=83.5 KiB (+83.5 KiB), count=109 (+109), average=784 B
101 /usr/lib/python3.4/unittest/mock.py:491: size=77.7 KiB (+77.7 KiB), count=143 (+143), average=557 B
102 /usr/lib/python3.4/urllib/parse.py:476: size=71.8 KiB (+71.8 KiB), count=969 (+969), average=76 B
103 /usr/lib/python3.4/contextlib.py:38: size=67.2 KiB (+67.2 KiB), count=126 (+126), average=546 B
104
Victor Stinner00773df2013-11-26 00:40:10 +0100105We can see that Python has loaded ``8.2 MiB`` of module data (bytecode and
106constants), and that this is ``4.4 MiB`` more than had been loaded before the
107tests, when the previous snapshot was taken. Similarly, the :mod:`linecache`
108module has cached ``940 KiB`` of Python source code to format tracebacks, all
109of it since the previous snapshot.
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100110
111If the system has little free memory, snapshots can be written on disk using
112the :meth:`Snapshot.dump` method to analyze the snapshot offline. Then use the
113:meth:`Snapshot.load` method reload the snapshot.
114
115
116Get the traceback of a memory block
Georg Brandl717e0282014-10-31 10:21:07 +0100117^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100118
119Code to display the traceback of the biggest memory block::
120
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100121 import tracemalloc
122
Victor Stinner3728d6c2013-11-23 12:37:20 +0100123 # Store 25 frames
124 tracemalloc.start(25)
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100125
126 # ... run your application ...
127
128 snapshot = tracemalloc.take_snapshot()
129 top_stats = snapshot.statistics('traceback')
130
131 # pick the biggest memory block
132 stat = top_stats[0]
133 print("%s memory blocks: %.1f KiB" % (stat.count, stat.size / 1024))
Victor Stinner23f628d2014-02-16 23:53:38 +0100134 for line in stat.traceback.format():
135 print(line)
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100136
137Example of output of the Python test suite (traceback limited to 25 frames)::
138
139 903 memory blocks: 870.1 KiB
140 File "<frozen importlib._bootstrap>", line 716
141 File "<frozen importlib._bootstrap>", line 1036
142 File "<frozen importlib._bootstrap>", line 934
143 File "<frozen importlib._bootstrap>", line 1068
144 File "<frozen importlib._bootstrap>", line 619
145 File "<frozen importlib._bootstrap>", line 1581
146 File "<frozen importlib._bootstrap>", line 1614
147 File "/usr/lib/python3.4/doctest.py", line 101
148 import pdb
149 File "<frozen importlib._bootstrap>", line 284
150 File "<frozen importlib._bootstrap>", line 938
151 File "<frozen importlib._bootstrap>", line 1068
152 File "<frozen importlib._bootstrap>", line 619
153 File "<frozen importlib._bootstrap>", line 1581
154 File "<frozen importlib._bootstrap>", line 1614
155 File "/usr/lib/python3.4/test/support/__init__.py", line 1728
156 import doctest
157 File "/usr/lib/python3.4/test/test_pickletools.py", line 21
158 support.run_doctest(pickletools)
159 File "/usr/lib/python3.4/test/regrtest.py", line 1276
160 test_runner()
161 File "/usr/lib/python3.4/test/regrtest.py", line 976
162 display_failure=not verbose)
163 File "/usr/lib/python3.4/test/regrtest.py", line 761
164 match_tests=ns.match_tests)
165 File "/usr/lib/python3.4/test/regrtest.py", line 1563
166 main()
167 File "/usr/lib/python3.4/test/__main__.py", line 3
168 regrtest.main_in_temp_cwd()
169 File "/usr/lib/python3.4/runpy.py", line 73
170 exec(code, run_globals)
171 File "/usr/lib/python3.4/runpy.py", line 160
172 "__main__", fname, loader, pkg_name)
173
Victor Stinner00773df2013-11-26 00:40:10 +0100174We can see that the most memory was allocated in the :mod:`importlib` module to
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100175load data (bytecode and constants) from modules: ``870 KiB``. The traceback is
Victor Stinner00773df2013-11-26 00:40:10 +0100176where the :mod:`importlib` loaded data most recently: on the ``import pdb``
177line of the :mod:`doctest` module. The traceback may change if a new module is
178loaded.
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100179
180
181Pretty top
Georg Brandl717e0282014-10-31 10:21:07 +0100182^^^^^^^^^^
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100183
184Code to display the 10 lines allocating the most memory with a pretty output,
185ignoring ``<frozen importlib._bootstrap>`` and ``<unknown>`` files::
186
Victor Stinner637d2e92014-03-11 08:12:48 +0100187 import linecache
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100188 import os
189 import tracemalloc
190
191 def display_top(snapshot, group_by='lineno', limit=10):
192 snapshot = snapshot.filter_traces((
193 tracemalloc.Filter(False, "<frozen importlib._bootstrap>"),
194 tracemalloc.Filter(False, "<unknown>"),
195 ))
196 top_stats = snapshot.statistics(group_by)
197
198 print("Top %s lines" % limit)
199 for index, stat in enumerate(top_stats[:limit], 1):
200 frame = stat.traceback[0]
201 # replace "/path/to/module/file.py" with "module/file.py"
202 filename = os.sep.join(frame.filename.split(os.sep)[-2:])
203 print("#%s: %s:%s: %.1f KiB"
Victor Stinnerf70200e2014-03-03 11:57:57 +0100204 % (index, filename, frame.lineno, stat.size / 1024))
Victor Stinner637d2e92014-03-11 08:12:48 +0100205 line = linecache.getline(frame.filename, frame.lineno).strip()
206 if line:
207 print(' %s' % line)
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100208
209 other = top_stats[limit:]
210 if other:
211 size = sum(stat.size for stat in other)
212 print("%s other: %.1f KiB" % (len(other), size / 1024))
213 total = sum(stat.size for stat in top_stats)
214 print("Total allocated size: %.1f KiB" % (total / 1024))
215
216 tracemalloc.start()
217
218 # ... run your application ...
219
220 snapshot = tracemalloc.take_snapshot()
Victor Stinnerf70200e2014-03-03 11:57:57 +0100221 display_top(snapshot)
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100222
223Example of output of the Python test suite::
224
Victor Stinner637d2e92014-03-11 08:12:48 +0100225 Top 10 lines
226 #1: Lib/base64.py:414: 419.8 KiB
227 _b85chars2 = [(a + b) for a in _b85chars for b in _b85chars]
228 #2: Lib/base64.py:306: 419.8 KiB
229 _a85chars2 = [(a + b) for a in _a85chars for b in _a85chars]
230 #3: collections/__init__.py:368: 293.6 KiB
231 exec(class_definition, namespace)
232 #4: Lib/abc.py:133: 115.2 KiB
233 cls = super().__new__(mcls, name, bases, namespace)
234 #5: unittest/case.py:574: 103.1 KiB
235 testMethod()
236 #6: Lib/linecache.py:127: 95.4 KiB
237 lines = fp.readlines()
238 #7: urllib/parse.py:476: 71.8 KiB
239 for a in _hexdig for b in _hexdig}
240 #8: <string>:5: 62.0 KiB
241 #9: Lib/_weakrefset.py:37: 60.0 KiB
242 self.data = set()
243 #10: Lib/base64.py:142: 59.8 KiB
244 _b32tab2 = [a + b for a in _b32tab for b in _b32tab]
245 6220 other: 3602.8 KiB
246 Total allocated size: 5303.1 KiB
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100247
248See :meth:`Snapshot.statistics` for more options.
249
250
251API
Georg Brandl717e0282014-10-31 10:21:07 +0100252---
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100253
254Functions
Georg Brandl717e0282014-10-31 10:21:07 +0100255^^^^^^^^^
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100256
257.. function:: clear_traces()
258
259 Clear traces of memory blocks allocated by Python.
260
261 See also :func:`stop`.
262
263
264.. function:: get_object_traceback(obj)
265
266 Get the traceback where the Python object *obj* was allocated.
267 Return a :class:`Traceback` instance, or ``None`` if the :mod:`tracemalloc`
268 module is not tracing memory allocations or did not trace the allocation of
269 the object.
270
271 See also :func:`gc.get_referrers` and :func:`sys.getsizeof` functions.
272
273
274.. function:: get_traceback_limit()
275
276 Get the maximum number of frames stored in the traceback of a trace.
277
Victor Stinner3728d6c2013-11-23 12:37:20 +0100278 The :mod:`tracemalloc` module must be tracing memory allocations to
279 get the limit, otherwise an exception is raised.
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100280
Victor Stinner3728d6c2013-11-23 12:37:20 +0100281 The limit is set by the :func:`start` function.
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100282
283
284.. function:: get_traced_memory()
285
Victor Stinner3c0481d2013-11-27 21:39:49 +0100286 Get the current size and peak size of memory blocks traced by the
287 :mod:`tracemalloc` module as a tuple: ``(current: int, peak: int)``.
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100288
289
290.. function:: get_tracemalloc_memory()
291
292 Get the memory usage in bytes of the :mod:`tracemalloc` module used to store
293 traces of memory blocks.
294 Return an :class:`int`.
295
296
297.. function:: is_tracing()
298
299 ``True`` if the :mod:`tracemalloc` module is tracing Python memory
300 allocations, ``False`` otherwise.
301
302 See also :func:`start` and :func:`stop` functions.
303
304
Victor Stinner3728d6c2013-11-23 12:37:20 +0100305.. function:: start(nframe: int=1)
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100306
Victor Stinner3728d6c2013-11-23 12:37:20 +0100307 Start tracing Python memory allocations: install hooks on Python memory
308 allocators. Collected tracebacks of traces will be limited to *nframe*
309 frames. By default, a trace of a memory block only stores the most recent
310 frame: the limit is ``1``. *nframe* must be greater or equal to ``1``.
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100311
312 Storing more than ``1`` frame is only useful to compute statistics grouped
313 by ``'traceback'`` or to compute cumulative statistics: see the
314 :meth:`Snapshot.compare_to` and :meth:`Snapshot.statistics` methods.
315
316 Storing more frames increases the memory and CPU overhead of the
317 :mod:`tracemalloc` module. Use the :func:`get_tracemalloc_memory` function
318 to measure how much memory is used by the :mod:`tracemalloc` module.
319
320 The :envvar:`PYTHONTRACEMALLOC` environment variable
321 (``PYTHONTRACEMALLOC=NFRAME``) and the :option:`-X` ``tracemalloc=NFRAME``
Victor Stinner3728d6c2013-11-23 12:37:20 +0100322 command line option can be used to start tracing at startup.
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100323
Victor Stinner3728d6c2013-11-23 12:37:20 +0100324 See also :func:`stop`, :func:`is_tracing` and :func:`get_traceback_limit`
325 functions.
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100326
327
328.. function:: stop()
329
330 Stop tracing Python memory allocations: uninstall hooks on Python memory
Victor Stinner00773df2013-11-26 00:40:10 +0100331 allocators. Also clears all previously collected traces of memory blocks
332 allocated by Python.
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100333
334 Call :func:`take_snapshot` function to take a snapshot of traces before
335 clearing them.
336
Victor Stinner00773df2013-11-26 00:40:10 +0100337 See also :func:`start`, :func:`is_tracing` and :func:`clear_traces`
338 functions.
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100339
340
341.. function:: take_snapshot()
342
343 Take a snapshot of traces of memory blocks allocated by Python. Return a new
344 :class:`Snapshot` instance.
345
346 The snapshot does not include memory blocks allocated before the
347 :mod:`tracemalloc` module started to trace memory allocations.
348
349 Tracebacks of traces are limited to :func:`get_traceback_limit` frames. Use
Victor Stinner3728d6c2013-11-23 12:37:20 +0100350 the *nframe* parameter of the :func:`start` function to store more frames.
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100351
352 The :mod:`tracemalloc` module must be tracing memory allocations to take a
Donald Stufft8b852f12014-05-20 12:58:38 -0400353 snapshot, see the :func:`start` function.
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100354
355 See also the :func:`get_object_traceback` function.
356
357
Victor Stinnere492ae52016-03-22 12:58:23 +0100358DomainFilter
359^^^^^^^^^^^^
360
361.. class:: DomainFilter(inclusive: bool, domain: int)
362
363 Filter traces of memory blocks by their address space (domain).
364
365 .. versionadded:: 3.6
366
367 .. attribute:: inclusive
368
369 If *inclusive* is ``True`` (include), match memory blocks allocated
370 in the address space :attr:`domain`.
371
372 If *inclusive* is ``False`` (exclude), match memory blocks not allocated
373 in the address space :attr:`domain`.
374
375 .. attribute:: domain
376
377 Address space of a memory block (``int``). Read-only property.
378
379
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100380Filter
Georg Brandl717e0282014-10-31 10:21:07 +0100381^^^^^^
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100382
Victor Stinnere492ae52016-03-22 12:58:23 +0100383.. class:: Filter(inclusive: bool, filename_pattern: str, lineno: int=None, all_frames: bool=False, domain: int=None)
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100384
385 Filter on traces of memory blocks.
386
387 See the :func:`fnmatch.fnmatch` function for the syntax of
Brett Cannonf299abd2015-04-13 14:21:02 -0400388 *filename_pattern*. The ``'.pyc'`` file extension is
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100389 replaced with ``'.py'``.
390
391 Examples:
392
393 * ``Filter(True, subprocess.__file__)`` only includes traces of the
394 :mod:`subprocess` module
395 * ``Filter(False, tracemalloc.__file__)`` excludes traces of the
396 :mod:`tracemalloc` module
397 * ``Filter(False, "<unknown>")`` excludes empty tracebacks
398
Brett Cannonf299abd2015-04-13 14:21:02 -0400399
400 .. versionchanged:: 3.5
401 The ``'.pyo'`` file extension is no longer replaced with ``'.py'``.
402
Victor Stinnere492ae52016-03-22 12:58:23 +0100403 .. versionchanged:: 3.6
404 Added the :attr:`domain` attribute.
405
406
407 .. attribute:: domain
408
409 Address space of a memory block (``int`` or ``None``).
410
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100411 .. attribute:: inclusive
412
Victor Stinnere492ae52016-03-22 12:58:23 +0100413 If *inclusive* is ``True`` (include), only match memory blocks allocated
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100414 in a file with a name matching :attr:`filename_pattern` at line number
415 :attr:`lineno`.
416
417 If *inclusive* is ``False`` (exclude), ignore memory blocks allocated in
418 a file with a name matching :attr:`filename_pattern` at line number
419 :attr:`lineno`.
420
421 .. attribute:: lineno
422
423 Line number (``int``) of the filter. If *lineno* is ``None``, the filter
424 matches any line number.
425
426 .. attribute:: filename_pattern
427
Victor Stinnere492ae52016-03-22 12:58:23 +0100428 Filename pattern of the filter (``str``). Read-only property.
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100429
430 .. attribute:: all_frames
431
432 If *all_frames* is ``True``, all frames of the traceback are checked. If
433 *all_frames* is ``False``, only the most recent frame is checked.
434
Victor Stinner5362abf2013-11-27 23:39:55 +0100435 This attribute has no effect if the traceback limit is ``1``. See the
436 :func:`get_traceback_limit` function and :attr:`Snapshot.traceback_limit`
437 attribute.
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100438
439
440Frame
Georg Brandl717e0282014-10-31 10:21:07 +0100441^^^^^
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100442
443.. class:: Frame
444
445 Frame of a traceback.
446
447 The :class:`Traceback` class is a sequence of :class:`Frame` instances.
448
449 .. attribute:: filename
450
451 Filename (``str``).
452
453 .. attribute:: lineno
454
455 Line number (``int``).
456
457
458Snapshot
Georg Brandl717e0282014-10-31 10:21:07 +0100459^^^^^^^^
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100460
461.. class:: Snapshot
462
463 Snapshot of traces of memory blocks allocated by Python.
464
465 The :func:`take_snapshot` function creates a snapshot instance.
466
467 .. method:: compare_to(old_snapshot: Snapshot, group_by: str, cumulative: bool=False)
468
469 Compute the differences with an old snapshot. Get statistics as a sorted
470 list of :class:`StatisticDiff` instances grouped by *group_by*.
471
Berker Peksag49008772014-11-10 23:15:32 +0200472 See the :meth:`Snapshot.statistics` method for *group_by* and *cumulative*
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100473 parameters.
474
475 The result is sorted from the biggest to the smallest by: absolute value
476 of :attr:`StatisticDiff.size_diff`, :attr:`StatisticDiff.size`, absolute
477 value of :attr:`StatisticDiff.count_diff`, :attr:`Statistic.count` and
478 then by :attr:`StatisticDiff.traceback`.
479
480
481 .. method:: dump(filename)
482
483 Write the snapshot into a file.
484
485 Use :meth:`load` to reload the snapshot.
486
487
488 .. method:: filter_traces(filters)
489
490 Create a new :class:`Snapshot` instance with a filtered :attr:`traces`
Victor Stinnere492ae52016-03-22 12:58:23 +0100491 sequence, *filters* is a list of :class:`DomainFilter` and
492 :class:`Filter` instances. If *filters* is an empty list, return a new
493 :class:`Snapshot` instance with a copy of the traces.
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100494
495 All inclusive filters are applied at once, a trace is ignored if no
496 inclusive filters match it. A trace is ignored if at least one exclusive
Martin Panter1f1177d2015-10-31 11:48:53 +0000497 filter matches it.
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100498
Victor Stinnere492ae52016-03-22 12:58:23 +0100499 .. versionchanged:: 3.6
500 :class:`DomainFilter` instances are now also accepted in *filters*.
501
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100502
503 .. classmethod:: load(filename)
504
505 Load a snapshot from a file.
506
507 See also :meth:`dump`.
508
509
510 .. method:: statistics(group_by: str, cumulative: bool=False)
511
512 Get statistics as a sorted list of :class:`Statistic` instances grouped
513 by *group_by*:
514
515 ===================== ========================
516 group_by description
517 ===================== ========================
518 ``'filename'`` filename
519 ``'lineno'`` filename and line number
520 ``'traceback'`` traceback
521 ===================== ========================
522
523 If *cumulative* is ``True``, cumulate size and count of memory blocks of
524 all frames of the traceback of a trace, not only the most recent frame.
525 The cumulative mode can only be used with *group_by* equals to
Victor Stinner8e3708d2013-11-26 00:45:47 +0100526 ``'filename'`` and ``'lineno'``.
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100527
528 The result is sorted from the biggest to the smallest by:
529 :attr:`Statistic.size`, :attr:`Statistic.count` and then by
530 :attr:`Statistic.traceback`.
531
532
533 .. attribute:: traceback_limit
534
535 Maximum number of frames stored in the traceback of :attr:`traces`:
536 result of the :func:`get_traceback_limit` when the snapshot was taken.
537
538 .. attribute:: traces
539
540 Traces of all memory blocks allocated by Python: sequence of
541 :class:`Trace` instances.
542
543 The sequence has an undefined order. Use the :meth:`Snapshot.statistics`
544 method to get a sorted list of statistics.
545
546
547Statistic
Georg Brandl717e0282014-10-31 10:21:07 +0100548^^^^^^^^^
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100549
550.. class:: Statistic
551
552 Statistic on memory allocations.
553
554 :func:`Snapshot.statistics` returns a list of :class:`Statistic` instances.
555
556 See also the :class:`StatisticDiff` class.
557
558 .. attribute:: count
559
560 Number of memory blocks (``int``).
561
562 .. attribute:: size
563
564 Total size of memory blocks in bytes (``int``).
565
566 .. attribute:: traceback
567
568 Traceback where the memory block was allocated, :class:`Traceback`
569 instance.
570
571
572StatisticDiff
Georg Brandl717e0282014-10-31 10:21:07 +0100573^^^^^^^^^^^^^
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100574
575.. class:: StatisticDiff
576
577 Statistic difference on memory allocations between an old and a new
578 :class:`Snapshot` instance.
579
580 :func:`Snapshot.compare_to` returns a list of :class:`StatisticDiff`
581 instances. See also the :class:`Statistic` class.
582
583 .. attribute:: count
584
585 Number of memory blocks in the new snapshot (``int``): ``0`` if
586 the memory blocks have been released in the new snapshot.
587
588 .. attribute:: count_diff
589
590 Difference of number of memory blocks between the old and the new
591 snapshots (``int``): ``0`` if the memory blocks have been allocated in
592 the new snapshot.
593
594 .. attribute:: size
595
596 Total size of memory blocks in bytes in the new snapshot (``int``):
597 ``0`` if the memory blocks have been released in the new snapshot.
598
599 .. attribute:: size_diff
600
601 Difference of total size of memory blocks in bytes between the old and
602 the new snapshots (``int``): ``0`` if the memory blocks have been
603 allocated in the new snapshot.
604
605 .. attribute:: traceback
606
607 Traceback where the memory blocks were allocated, :class:`Traceback`
608 instance.
609
610
611Trace
Georg Brandl717e0282014-10-31 10:21:07 +0100612^^^^^
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100613
614.. class:: Trace
615
616 Trace of a memory block.
617
618 The :attr:`Snapshot.traces` attribute is a sequence of :class:`Trace`
619 instances.
620
621 .. attribute:: size
622
623 Size of the memory block in bytes (``int``).
624
625 .. attribute:: traceback
626
627 Traceback where the memory block was allocated, :class:`Traceback`
628 instance.
629
630
631Traceback
Georg Brandl717e0282014-10-31 10:21:07 +0100632^^^^^^^^^
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100633
634.. class:: Traceback
635
636 Sequence of :class:`Frame` instances sorted from the most recent frame to
637 the oldest frame.
638
639 A traceback contains at least ``1`` frame. If the ``tracemalloc`` module
640 failed to get a frame, the filename ``"<unknown>"`` at line number ``0`` is
641 used.
642
643 When a snapshot is taken, tracebacks of traces are limited to
644 :func:`get_traceback_limit` frames. See the :func:`take_snapshot` function.
645
646 The :attr:`Trace.traceback` attribute is an instance of :class:`Traceback`
647 instance.
648
Victor Stinner23f628d2014-02-16 23:53:38 +0100649 .. method:: format(limit=None)
650
651 Format the traceback as a list of lines with newlines. Use the
652 :mod:`linecache` module to retrieve lines from the source code. If
653 *limit* is set, only format the *limit* most recent frames.
654
655 Similar to the :func:`traceback.format_tb` function, except that
Martin Panterd5db1472016-02-08 01:34:09 +0000656 :meth:`.format` does not include newlines.
Victor Stinner23f628d2014-02-16 23:53:38 +0100657
658 Example::
659
660 print("Traceback (most recent call first):")
661 for line in traceback:
662 print(line)
663
664 Output::
665
666 Traceback (most recent call first):
667 File "test.py", line 9
668 obj = Object()
669 File "test.py", line 12
670 tb = tracemalloc.get_object_traceback(f())