blob: 3eee9457fb29a8dae35ef1e84a8b12780849cb93 [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
Terry Jan Reedyfa089b92016-06-11 15:02:54 -04009**Source code:** :source:`Lib/tracemalloc.py`
10
11--------------
12
Victor Stinnered3b0bc2013-11-23 12:27:24 +010013The tracemalloc module is a debug tool to trace memory blocks allocated by
14Python. It provides the following information:
15
16* Traceback where an object was allocated
17* Statistics on allocated memory blocks per filename and per line number:
18 total size, number and average size of allocated memory blocks
19* Compute the differences between two snapshots to detect memory leaks
20
21To trace most memory blocks allocated by Python, the module should be started
22as early as possible by setting the :envvar:`PYTHONTRACEMALLOC` environment
23variable to ``1``, or by using :option:`-X` ``tracemalloc`` command line
24option. The :func:`tracemalloc.start` function can be called at runtime to
25start tracing Python memory allocations.
26
27By default, a trace of an allocated memory block only stores the most recent
28frame (1 frame). To store 25 frames at startup: set the
29:envvar:`PYTHONTRACEMALLOC` environment variable to ``25``, or use the
Victor Stinner3728d6c2013-11-23 12:37:20 +010030:option:`-X` ``tracemalloc=25`` command line option.
Victor Stinnered3b0bc2013-11-23 12:27:24 +010031
Victor Stinnered3b0bc2013-11-23 12:27:24 +010032
33Examples
Georg Brandl717e0282014-10-31 10:21:07 +010034--------
Victor Stinnered3b0bc2013-11-23 12:27:24 +010035
36Display the top 10
Georg Brandl717e0282014-10-31 10:21:07 +010037^^^^^^^^^^^^^^^^^^
Victor Stinnered3b0bc2013-11-23 12:27:24 +010038
39Display the 10 files allocating the most memory::
40
41 import tracemalloc
42
43 tracemalloc.start()
44
45 # ... run your application ...
46
47 snapshot = tracemalloc.take_snapshot()
48 top_stats = snapshot.statistics('lineno')
49
50 print("[ Top 10 ]")
51 for stat in top_stats[:10]:
52 print(stat)
53
54
55Example of output of the Python test suite::
56
57 [ Top 10 ]
58 <frozen importlib._bootstrap>:716: size=4855 KiB, count=39328, average=126 B
59 <frozen importlib._bootstrap>:284: size=521 KiB, count=3199, average=167 B
60 /usr/lib/python3.4/collections/__init__.py:368: size=244 KiB, count=2315, average=108 B
61 /usr/lib/python3.4/unittest/case.py:381: size=185 KiB, count=779, average=243 B
62 /usr/lib/python3.4/unittest/case.py:402: size=154 KiB, count=378, average=416 B
63 /usr/lib/python3.4/abc.py:133: size=88.7 KiB, count=347, average=262 B
64 <frozen importlib._bootstrap>:1446: size=70.4 KiB, count=911, average=79 B
65 <frozen importlib._bootstrap>:1454: size=52.0 KiB, count=25, average=2131 B
66 <string>:5: size=49.7 KiB, count=148, average=344 B
67 /usr/lib/python3.4/sysconfig.py:411: size=48.0 KiB, count=1, average=48.0 KiB
68
Victor Stinner440d7032016-12-30 02:14:59 +010069We can see that Python loaded ``4855 KiB`` data (bytecode and constants) from
Victor Stinnered3b0bc2013-11-23 12:27:24 +010070modules and that the :mod:`collections` module allocated ``244 KiB`` to build
71:class:`~collections.namedtuple` types.
72
73See :meth:`Snapshot.statistics` for more options.
74
75
76Compute differences
Georg Brandl717e0282014-10-31 10:21:07 +010077^^^^^^^^^^^^^^^^^^^
Victor Stinnered3b0bc2013-11-23 12:27:24 +010078
79Take two snapshots and display the differences::
80
81 import tracemalloc
82 tracemalloc.start()
83 # ... start your application ...
84
85 snapshot1 = tracemalloc.take_snapshot()
86 # ... call the function leaking memory ...
87 snapshot2 = tracemalloc.take_snapshot()
88
89 top_stats = snapshot2.compare_to(snapshot1, 'lineno')
90
91 print("[ Top 10 differences ]")
92 for stat in top_stats[:10]:
93 print(stat)
94
95Example of output before/after running some tests of the Python test suite::
96
97 [ Top 10 differences ]
98 <frozen importlib._bootstrap>:716: size=8173 KiB (+4428 KiB), count=71332 (+39369), average=117 B
99 /usr/lib/python3.4/linecache.py:127: size=940 KiB (+940 KiB), count=8106 (+8106), average=119 B
100 /usr/lib/python3.4/unittest/case.py:571: size=298 KiB (+298 KiB), count=589 (+589), average=519 B
101 <frozen importlib._bootstrap>:284: size=1005 KiB (+166 KiB), count=7423 (+1526), average=139 B
102 /usr/lib/python3.4/mimetypes.py:217: size=112 KiB (+112 KiB), count=1334 (+1334), average=86 B
103 /usr/lib/python3.4/http/server.py:848: size=96.0 KiB (+96.0 KiB), count=1 (+1), average=96.0 KiB
104 /usr/lib/python3.4/inspect.py:1465: size=83.5 KiB (+83.5 KiB), count=109 (+109), average=784 B
105 /usr/lib/python3.4/unittest/mock.py:491: size=77.7 KiB (+77.7 KiB), count=143 (+143), average=557 B
106 /usr/lib/python3.4/urllib/parse.py:476: size=71.8 KiB (+71.8 KiB), count=969 (+969), average=76 B
107 /usr/lib/python3.4/contextlib.py:38: size=67.2 KiB (+67.2 KiB), count=126 (+126), average=546 B
108
Victor Stinner440d7032016-12-30 02:14:59 +0100109We can see that Python has loaded ``8173 KiB`` of module data (bytecode and
110constants), and that this is ``4428 KiB`` more than had been loaded before the
Victor Stinner00773df2013-11-26 00:40:10 +0100111tests, when the previous snapshot was taken. Similarly, the :mod:`linecache`
112module has cached ``940 KiB`` of Python source code to format tracebacks, all
113of it since the previous snapshot.
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100114
115If the system has little free memory, snapshots can be written on disk using
116the :meth:`Snapshot.dump` method to analyze the snapshot offline. Then use the
117:meth:`Snapshot.load` method reload the snapshot.
118
119
120Get the traceback of a memory block
Georg Brandl717e0282014-10-31 10:21:07 +0100121^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100122
123Code to display the traceback of the biggest memory block::
124
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100125 import tracemalloc
126
Victor Stinner3728d6c2013-11-23 12:37:20 +0100127 # Store 25 frames
128 tracemalloc.start(25)
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100129
130 # ... run your application ...
131
132 snapshot = tracemalloc.take_snapshot()
133 top_stats = snapshot.statistics('traceback')
134
135 # pick the biggest memory block
136 stat = top_stats[0]
137 print("%s memory blocks: %.1f KiB" % (stat.count, stat.size / 1024))
Victor Stinner23f628d2014-02-16 23:53:38 +0100138 for line in stat.traceback.format():
139 print(line)
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100140
141Example of output of the Python test suite (traceback limited to 25 frames)::
142
143 903 memory blocks: 870.1 KiB
144 File "<frozen importlib._bootstrap>", line 716
145 File "<frozen importlib._bootstrap>", line 1036
146 File "<frozen importlib._bootstrap>", line 934
147 File "<frozen importlib._bootstrap>", line 1068
148 File "<frozen importlib._bootstrap>", line 619
149 File "<frozen importlib._bootstrap>", line 1581
150 File "<frozen importlib._bootstrap>", line 1614
151 File "/usr/lib/python3.4/doctest.py", line 101
152 import pdb
153 File "<frozen importlib._bootstrap>", line 284
154 File "<frozen importlib._bootstrap>", line 938
155 File "<frozen importlib._bootstrap>", line 1068
156 File "<frozen importlib._bootstrap>", line 619
157 File "<frozen importlib._bootstrap>", line 1581
158 File "<frozen importlib._bootstrap>", line 1614
159 File "/usr/lib/python3.4/test/support/__init__.py", line 1728
160 import doctest
161 File "/usr/lib/python3.4/test/test_pickletools.py", line 21
162 support.run_doctest(pickletools)
163 File "/usr/lib/python3.4/test/regrtest.py", line 1276
164 test_runner()
165 File "/usr/lib/python3.4/test/regrtest.py", line 976
166 display_failure=not verbose)
167 File "/usr/lib/python3.4/test/regrtest.py", line 761
168 match_tests=ns.match_tests)
169 File "/usr/lib/python3.4/test/regrtest.py", line 1563
170 main()
171 File "/usr/lib/python3.4/test/__main__.py", line 3
172 regrtest.main_in_temp_cwd()
173 File "/usr/lib/python3.4/runpy.py", line 73
174 exec(code, run_globals)
175 File "/usr/lib/python3.4/runpy.py", line 160
176 "__main__", fname, loader, pkg_name)
177
Victor Stinner00773df2013-11-26 00:40:10 +0100178We can see that the most memory was allocated in the :mod:`importlib` module to
Victor Stinner440d7032016-12-30 02:14:59 +0100179load data (bytecode and constants) from modules: ``870.1 KiB``. The traceback is
Victor Stinner00773df2013-11-26 00:40:10 +0100180where the :mod:`importlib` loaded data most recently: on the ``import pdb``
181line of the :mod:`doctest` module. The traceback may change if a new module is
182loaded.
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100183
184
185Pretty top
Georg Brandl717e0282014-10-31 10:21:07 +0100186^^^^^^^^^^
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100187
188Code to display the 10 lines allocating the most memory with a pretty output,
189ignoring ``<frozen importlib._bootstrap>`` and ``<unknown>`` files::
190
Victor Stinner637d2e92014-03-11 08:12:48 +0100191 import linecache
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100192 import os
193 import tracemalloc
194
Victor Stinner440d7032016-12-30 02:14:59 +0100195 def display_top(snapshot, key_type='lineno', limit=10):
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100196 snapshot = snapshot.filter_traces((
197 tracemalloc.Filter(False, "<frozen importlib._bootstrap>"),
198 tracemalloc.Filter(False, "<unknown>"),
199 ))
Victor Stinner440d7032016-12-30 02:14:59 +0100200 top_stats = snapshot.statistics(key_type)
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100201
202 print("Top %s lines" % limit)
203 for index, stat in enumerate(top_stats[:limit], 1):
204 frame = stat.traceback[0]
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100205 print("#%s: %s:%s: %.1f KiB"
Adam Johnsond06eec22020-03-10 18:18:50 +0000206 % (index, frame.filename, frame.lineno, stat.size / 1024))
Victor Stinner637d2e92014-03-11 08:12:48 +0100207 line = linecache.getline(frame.filename, frame.lineno).strip()
208 if line:
209 print(' %s' % line)
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100210
211 other = top_stats[limit:]
212 if other:
213 size = sum(stat.size for stat in other)
214 print("%s other: %.1f KiB" % (len(other), size / 1024))
215 total = sum(stat.size for stat in top_stats)
216 print("Total allocated size: %.1f KiB" % (total / 1024))
217
218 tracemalloc.start()
219
220 # ... run your application ...
221
222 snapshot = tracemalloc.take_snapshot()
Victor Stinnerf70200e2014-03-03 11:57:57 +0100223 display_top(snapshot)
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100224
225Example of output of the Python test suite::
226
Victor Stinner637d2e92014-03-11 08:12:48 +0100227 Top 10 lines
228 #1: Lib/base64.py:414: 419.8 KiB
229 _b85chars2 = [(a + b) for a in _b85chars for b in _b85chars]
230 #2: Lib/base64.py:306: 419.8 KiB
231 _a85chars2 = [(a + b) for a in _a85chars for b in _a85chars]
232 #3: collections/__init__.py:368: 293.6 KiB
233 exec(class_definition, namespace)
234 #4: Lib/abc.py:133: 115.2 KiB
235 cls = super().__new__(mcls, name, bases, namespace)
236 #5: unittest/case.py:574: 103.1 KiB
237 testMethod()
238 #6: Lib/linecache.py:127: 95.4 KiB
239 lines = fp.readlines()
240 #7: urllib/parse.py:476: 71.8 KiB
241 for a in _hexdig for b in _hexdig}
242 #8: <string>:5: 62.0 KiB
243 #9: Lib/_weakrefset.py:37: 60.0 KiB
244 self.data = set()
245 #10: Lib/base64.py:142: 59.8 KiB
246 _b32tab2 = [a + b for a in _b32tab for b in _b32tab]
247 6220 other: 3602.8 KiB
248 Total allocated size: 5303.1 KiB
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100249
250See :meth:`Snapshot.statistics` for more options.
251
252
253API
Georg Brandl717e0282014-10-31 10:21:07 +0100254---
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100255
256Functions
Georg Brandl717e0282014-10-31 10:21:07 +0100257^^^^^^^^^
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100258
259.. function:: clear_traces()
260
261 Clear traces of memory blocks allocated by Python.
262
263 See also :func:`stop`.
264
265
266.. function:: get_object_traceback(obj)
267
268 Get the traceback where the Python object *obj* was allocated.
269 Return a :class:`Traceback` instance, or ``None`` if the :mod:`tracemalloc`
270 module is not tracing memory allocations or did not trace the allocation of
271 the object.
272
273 See also :func:`gc.get_referrers` and :func:`sys.getsizeof` functions.
274
275
276.. function:: get_traceback_limit()
277
278 Get the maximum number of frames stored in the traceback of a trace.
279
Victor Stinner3728d6c2013-11-23 12:37:20 +0100280 The :mod:`tracemalloc` module must be tracing memory allocations to
281 get the limit, otherwise an exception is raised.
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100282
Victor Stinner3728d6c2013-11-23 12:37:20 +0100283 The limit is set by the :func:`start` function.
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100284
285
286.. function:: get_traced_memory()
287
Victor Stinner3c0481d2013-11-27 21:39:49 +0100288 Get the current size and peak size of memory blocks traced by the
289 :mod:`tracemalloc` module as a tuple: ``(current: int, peak: int)``.
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100290
291
292.. function:: get_tracemalloc_memory()
293
294 Get the memory usage in bytes of the :mod:`tracemalloc` module used to store
295 traces of memory blocks.
296 Return an :class:`int`.
297
298
299.. function:: is_tracing()
300
301 ``True`` if the :mod:`tracemalloc` module is tracing Python memory
302 allocations, ``False`` otherwise.
303
304 See also :func:`start` and :func:`stop` functions.
305
306
Victor Stinner3728d6c2013-11-23 12:37:20 +0100307.. function:: start(nframe: int=1)
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100308
Victor Stinner3728d6c2013-11-23 12:37:20 +0100309 Start tracing Python memory allocations: install hooks on Python memory
310 allocators. Collected tracebacks of traces will be limited to *nframe*
311 frames. By default, a trace of a memory block only stores the most recent
312 frame: the limit is ``1``. *nframe* must be greater or equal to ``1``.
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100313
Julien Danjou8d59eb12019-10-15 14:00:16 +0200314 You can still read the original number of total frames that composed the
315 traceback by looking at the :attr:`Traceback.total_nframe` attribute.
316
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100317 Storing more than ``1`` frame is only useful to compute statistics grouped
318 by ``'traceback'`` or to compute cumulative statistics: see the
319 :meth:`Snapshot.compare_to` and :meth:`Snapshot.statistics` methods.
320
321 Storing more frames increases the memory and CPU overhead of the
322 :mod:`tracemalloc` module. Use the :func:`get_tracemalloc_memory` function
323 to measure how much memory is used by the :mod:`tracemalloc` module.
324
325 The :envvar:`PYTHONTRACEMALLOC` environment variable
326 (``PYTHONTRACEMALLOC=NFRAME``) and the :option:`-X` ``tracemalloc=NFRAME``
Victor Stinner3728d6c2013-11-23 12:37:20 +0100327 command line option can be used to start tracing at startup.
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100328
Victor Stinner3728d6c2013-11-23 12:37:20 +0100329 See also :func:`stop`, :func:`is_tracing` and :func:`get_traceback_limit`
330 functions.
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100331
332
333.. function:: stop()
334
335 Stop tracing Python memory allocations: uninstall hooks on Python memory
Victor Stinner00773df2013-11-26 00:40:10 +0100336 allocators. Also clears all previously collected traces of memory blocks
337 allocated by Python.
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100338
339 Call :func:`take_snapshot` function to take a snapshot of traces before
340 clearing them.
341
Victor Stinner00773df2013-11-26 00:40:10 +0100342 See also :func:`start`, :func:`is_tracing` and :func:`clear_traces`
343 functions.
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100344
345
346.. function:: take_snapshot()
347
348 Take a snapshot of traces of memory blocks allocated by Python. Return a new
349 :class:`Snapshot` instance.
350
351 The snapshot does not include memory blocks allocated before the
352 :mod:`tracemalloc` module started to trace memory allocations.
353
354 Tracebacks of traces are limited to :func:`get_traceback_limit` frames. Use
Victor Stinner3728d6c2013-11-23 12:37:20 +0100355 the *nframe* parameter of the :func:`start` function to store more frames.
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100356
357 The :mod:`tracemalloc` module must be tracing memory allocations to take a
Donald Stufft8b852f12014-05-20 12:58:38 -0400358 snapshot, see the :func:`start` function.
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100359
360 See also the :func:`get_object_traceback` function.
361
362
Victor Stinnere492ae52016-03-22 12:58:23 +0100363DomainFilter
364^^^^^^^^^^^^
365
366.. class:: DomainFilter(inclusive: bool, domain: int)
367
368 Filter traces of memory blocks by their address space (domain).
369
370 .. versionadded:: 3.6
371
372 .. attribute:: inclusive
373
374 If *inclusive* is ``True`` (include), match memory blocks allocated
375 in the address space :attr:`domain`.
376
377 If *inclusive* is ``False`` (exclude), match memory blocks not allocated
378 in the address space :attr:`domain`.
379
380 .. attribute:: domain
381
382 Address space of a memory block (``int``). Read-only property.
383
384
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100385Filter
Georg Brandl717e0282014-10-31 10:21:07 +0100386^^^^^^
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100387
Victor Stinnere492ae52016-03-22 12:58:23 +0100388.. class:: Filter(inclusive: bool, filename_pattern: str, lineno: int=None, all_frames: bool=False, domain: int=None)
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100389
390 Filter on traces of memory blocks.
391
392 See the :func:`fnmatch.fnmatch` function for the syntax of
Brett Cannonf299abd2015-04-13 14:21:02 -0400393 *filename_pattern*. The ``'.pyc'`` file extension is
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100394 replaced with ``'.py'``.
395
396 Examples:
397
398 * ``Filter(True, subprocess.__file__)`` only includes traces of the
399 :mod:`subprocess` module
400 * ``Filter(False, tracemalloc.__file__)`` excludes traces of the
401 :mod:`tracemalloc` module
402 * ``Filter(False, "<unknown>")`` excludes empty tracebacks
403
Brett Cannonf299abd2015-04-13 14:21:02 -0400404
405 .. versionchanged:: 3.5
406 The ``'.pyo'`` file extension is no longer replaced with ``'.py'``.
407
Victor Stinnere492ae52016-03-22 12:58:23 +0100408 .. versionchanged:: 3.6
409 Added the :attr:`domain` attribute.
410
411
412 .. attribute:: domain
413
414 Address space of a memory block (``int`` or ``None``).
415
Victor Stinner5ea4c062017-06-20 17:46:36 +0200416 tracemalloc uses the domain ``0`` to trace memory allocations made by
417 Python. C extensions can use other domains to trace other resources.
418
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100419 .. attribute:: inclusive
420
Victor Stinnere492ae52016-03-22 12:58:23 +0100421 If *inclusive* is ``True`` (include), only match memory blocks allocated
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100422 in a file with a name matching :attr:`filename_pattern` at line number
423 :attr:`lineno`.
424
425 If *inclusive* is ``False`` (exclude), ignore memory blocks allocated in
426 a file with a name matching :attr:`filename_pattern` at line number
427 :attr:`lineno`.
428
429 .. attribute:: lineno
430
431 Line number (``int``) of the filter. If *lineno* is ``None``, the filter
432 matches any line number.
433
434 .. attribute:: filename_pattern
435
Victor Stinnere492ae52016-03-22 12:58:23 +0100436 Filename pattern of the filter (``str``). Read-only property.
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100437
438 .. attribute:: all_frames
439
440 If *all_frames* is ``True``, all frames of the traceback are checked. If
441 *all_frames* is ``False``, only the most recent frame is checked.
442
Victor Stinner5362abf2013-11-27 23:39:55 +0100443 This attribute has no effect if the traceback limit is ``1``. See the
444 :func:`get_traceback_limit` function and :attr:`Snapshot.traceback_limit`
445 attribute.
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100446
447
448Frame
Georg Brandl717e0282014-10-31 10:21:07 +0100449^^^^^
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100450
451.. class:: Frame
452
453 Frame of a traceback.
454
455 The :class:`Traceback` class is a sequence of :class:`Frame` instances.
456
457 .. attribute:: filename
458
459 Filename (``str``).
460
461 .. attribute:: lineno
462
463 Line number (``int``).
464
465
466Snapshot
Georg Brandl717e0282014-10-31 10:21:07 +0100467^^^^^^^^
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100468
469.. class:: Snapshot
470
471 Snapshot of traces of memory blocks allocated by Python.
472
473 The :func:`take_snapshot` function creates a snapshot instance.
474
Victor Stinner440d7032016-12-30 02:14:59 +0100475 .. method:: compare_to(old_snapshot: Snapshot, key_type: str, cumulative: bool=False)
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100476
477 Compute the differences with an old snapshot. Get statistics as a sorted
Victor Stinner440d7032016-12-30 02:14:59 +0100478 list of :class:`StatisticDiff` instances grouped by *key_type*.
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100479
Victor Stinner440d7032016-12-30 02:14:59 +0100480 See the :meth:`Snapshot.statistics` method for *key_type* and *cumulative*
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100481 parameters.
482
483 The result is sorted from the biggest to the smallest by: absolute value
484 of :attr:`StatisticDiff.size_diff`, :attr:`StatisticDiff.size`, absolute
485 value of :attr:`StatisticDiff.count_diff`, :attr:`Statistic.count` and
486 then by :attr:`StatisticDiff.traceback`.
487
488
489 .. method:: dump(filename)
490
491 Write the snapshot into a file.
492
493 Use :meth:`load` to reload the snapshot.
494
495
496 .. method:: filter_traces(filters)
497
498 Create a new :class:`Snapshot` instance with a filtered :attr:`traces`
Victor Stinnere492ae52016-03-22 12:58:23 +0100499 sequence, *filters* is a list of :class:`DomainFilter` and
500 :class:`Filter` instances. If *filters* is an empty list, return a new
501 :class:`Snapshot` instance with a copy of the traces.
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100502
503 All inclusive filters are applied at once, a trace is ignored if no
504 inclusive filters match it. A trace is ignored if at least one exclusive
Martin Panter1f1177d2015-10-31 11:48:53 +0000505 filter matches it.
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100506
Victor Stinnere492ae52016-03-22 12:58:23 +0100507 .. versionchanged:: 3.6
508 :class:`DomainFilter` instances are now also accepted in *filters*.
509
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100510
511 .. classmethod:: load(filename)
512
513 Load a snapshot from a file.
514
515 See also :meth:`dump`.
516
517
Victor Stinner440d7032016-12-30 02:14:59 +0100518 .. method:: statistics(key_type: str, cumulative: bool=False)
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100519
520 Get statistics as a sorted list of :class:`Statistic` instances grouped
Victor Stinner440d7032016-12-30 02:14:59 +0100521 by *key_type*:
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100522
523 ===================== ========================
Victor Stinner440d7032016-12-30 02:14:59 +0100524 key_type description
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100525 ===================== ========================
526 ``'filename'`` filename
527 ``'lineno'`` filename and line number
528 ``'traceback'`` traceback
529 ===================== ========================
530
531 If *cumulative* is ``True``, cumulate size and count of memory blocks of
532 all frames of the traceback of a trace, not only the most recent frame.
Victor Stinner440d7032016-12-30 02:14:59 +0100533 The cumulative mode can only be used with *key_type* equals to
Victor Stinner8e3708d2013-11-26 00:45:47 +0100534 ``'filename'`` and ``'lineno'``.
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100535
536 The result is sorted from the biggest to the smallest by:
537 :attr:`Statistic.size`, :attr:`Statistic.count` and then by
538 :attr:`Statistic.traceback`.
539
540
541 .. attribute:: traceback_limit
542
543 Maximum number of frames stored in the traceback of :attr:`traces`:
544 result of the :func:`get_traceback_limit` when the snapshot was taken.
545
546 .. attribute:: traces
547
548 Traces of all memory blocks allocated by Python: sequence of
549 :class:`Trace` instances.
550
551 The sequence has an undefined order. Use the :meth:`Snapshot.statistics`
552 method to get a sorted list of statistics.
553
554
555Statistic
Georg Brandl717e0282014-10-31 10:21:07 +0100556^^^^^^^^^
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100557
558.. class:: Statistic
559
560 Statistic on memory allocations.
561
562 :func:`Snapshot.statistics` returns a list of :class:`Statistic` instances.
563
564 See also the :class:`StatisticDiff` class.
565
566 .. attribute:: count
567
568 Number of memory blocks (``int``).
569
570 .. attribute:: size
571
572 Total size of memory blocks in bytes (``int``).
573
574 .. attribute:: traceback
575
576 Traceback where the memory block was allocated, :class:`Traceback`
577 instance.
578
579
580StatisticDiff
Georg Brandl717e0282014-10-31 10:21:07 +0100581^^^^^^^^^^^^^
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100582
583.. class:: StatisticDiff
584
585 Statistic difference on memory allocations between an old and a new
586 :class:`Snapshot` instance.
587
588 :func:`Snapshot.compare_to` returns a list of :class:`StatisticDiff`
589 instances. See also the :class:`Statistic` class.
590
591 .. attribute:: count
592
593 Number of memory blocks in the new snapshot (``int``): ``0`` if
594 the memory blocks have been released in the new snapshot.
595
596 .. attribute:: count_diff
597
598 Difference of number of memory blocks between the old and the new
599 snapshots (``int``): ``0`` if the memory blocks have been allocated in
600 the new snapshot.
601
602 .. attribute:: size
603
604 Total size of memory blocks in bytes in the new snapshot (``int``):
605 ``0`` if the memory blocks have been released in the new snapshot.
606
607 .. attribute:: size_diff
608
609 Difference of total size of memory blocks in bytes between the old and
610 the new snapshots (``int``): ``0`` if the memory blocks have been
611 allocated in the new snapshot.
612
613 .. attribute:: traceback
614
615 Traceback where the memory blocks were allocated, :class:`Traceback`
616 instance.
617
618
619Trace
Georg Brandl717e0282014-10-31 10:21:07 +0100620^^^^^
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100621
622.. class:: Trace
623
624 Trace of a memory block.
625
626 The :attr:`Snapshot.traces` attribute is a sequence of :class:`Trace`
627 instances.
628
Victor Stinner5ea4c062017-06-20 17:46:36 +0200629 .. versionchanged:: 3.6
630 Added the :attr:`domain` attribute.
631
632 .. attribute:: domain
633
634 Address space of a memory block (``int``). Read-only property.
635
636 tracemalloc uses the domain ``0`` to trace memory allocations made by
637 Python. C extensions can use other domains to trace other resources.
638
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100639 .. attribute:: size
640
641 Size of the memory block in bytes (``int``).
642
643 .. attribute:: traceback
644
645 Traceback where the memory block was allocated, :class:`Traceback`
646 instance.
647
648
649Traceback
Georg Brandl717e0282014-10-31 10:21:07 +0100650^^^^^^^^^
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100651
652.. class:: Traceback
653
Jesse-Bakker706e10b2017-11-30 00:05:07 +0100654 Sequence of :class:`Frame` instances sorted from the oldest frame to the
655 most recent frame.
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100656
657 A traceback contains at least ``1`` frame. If the ``tracemalloc`` module
658 failed to get a frame, the filename ``"<unknown>"`` at line number ``0`` is
659 used.
660
661 When a snapshot is taken, tracebacks of traces are limited to
662 :func:`get_traceback_limit` frames. See the :func:`take_snapshot` function.
Julien Danjou8d59eb12019-10-15 14:00:16 +0200663 The original number of frames of the traceback is stored in the
664 :attr:`Traceback.total_nframe` attribute. That allows to know if a traceback
665 has been truncated by the traceback limit.
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100666
667 The :attr:`Trace.traceback` attribute is an instance of :class:`Traceback`
668 instance.
669
Jesse-Bakker706e10b2017-11-30 00:05:07 +0100670 .. versionchanged:: 3.7
671 Frames are now sorted from the oldest to the most recent, instead of most recent to oldest.
Victor Stinner23f628d2014-02-16 23:53:38 +0100672
Julien Danjou8d59eb12019-10-15 14:00:16 +0200673 .. attribute:: total_nframe
674
675 Total number of frames that composed the traceback before truncation.
676 This attribute can be set to ``None`` if the information is not
677 available.
678
679 .. versionchanged:: 3.9
680 The :attr:`Traceback.total_nframe` attribute was added.
681
Jesse-Bakker706e10b2017-11-30 00:05:07 +0100682 .. method:: format(limit=None, most_recent_first=False)
683
684 Format the traceback as a list of lines with newlines. Use the
685 :mod:`linecache` module to retrieve lines from the source code.
686 If *limit* is set, format the *limit* most recent frames if *limit*
687 is positive. Otherwise, format the ``abs(limit)`` oldest frames.
688 If *most_recent_first* is ``True``, the order of the formatted frames
689 is reversed, returning the most recent frame first instead of last.
Victor Stinner23f628d2014-02-16 23:53:38 +0100690
691 Similar to the :func:`traceback.format_tb` function, except that
Martin Panterd5db1472016-02-08 01:34:09 +0000692 :meth:`.format` does not include newlines.
Victor Stinner23f628d2014-02-16 23:53:38 +0100693
694 Example::
695
696 print("Traceback (most recent call first):")
697 for line in traceback:
698 print(line)
699
700 Output::
701
702 Traceback (most recent call first):
703 File "test.py", line 9
704 obj = Object()
705 File "test.py", line 12
706 tb = tracemalloc.get_object_traceback(f())