blob: a04a4327167b8119cf67d732ed8521138eab24f2 [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 Stinnera91ff142014-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
Larry Hastings3732ed22014-03-15 21:13:56 -0700187 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 Stinneradb2e2a2014-03-03 11:57:57 +0100204 % (index, filename, frame.lineno, stat.size / 1024))
Larry Hastings3732ed22014-03-15 21:13:56 -0700205 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 Stinneradb2e2a2014-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
Larry Hastings3732ed22014-03-15 21:13:56 -0700225 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
Senthil Kumaranb4760ef2015-06-14 17:35:37 -0700353 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
358Filter
Georg Brandl717e0282014-10-31 10:21:07 +0100359^^^^^^
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100360
361.. class:: Filter(inclusive: bool, filename_pattern: str, lineno: int=None, all_frames: bool=False)
362
363 Filter on traces of memory blocks.
364
365 See the :func:`fnmatch.fnmatch` function for the syntax of
366 *filename_pattern*. The ``'.pyc'`` and ``'.pyo'`` file extensions are
367 replaced with ``'.py'``.
368
369 Examples:
370
371 * ``Filter(True, subprocess.__file__)`` only includes traces of the
372 :mod:`subprocess` module
373 * ``Filter(False, tracemalloc.__file__)`` excludes traces of the
374 :mod:`tracemalloc` module
375 * ``Filter(False, "<unknown>")`` excludes empty tracebacks
376
377 .. attribute:: inclusive
378
379 If *inclusive* is ``True`` (include), only trace memory blocks allocated
380 in a file with a name matching :attr:`filename_pattern` at line number
381 :attr:`lineno`.
382
383 If *inclusive* is ``False`` (exclude), ignore memory blocks allocated in
384 a file with a name matching :attr:`filename_pattern` at line number
385 :attr:`lineno`.
386
387 .. attribute:: lineno
388
389 Line number (``int``) of the filter. If *lineno* is ``None``, the filter
390 matches any line number.
391
392 .. attribute:: filename_pattern
393
394 Filename pattern of the filter (``str``).
395
396 .. attribute:: all_frames
397
398 If *all_frames* is ``True``, all frames of the traceback are checked. If
399 *all_frames* is ``False``, only the most recent frame is checked.
400
Victor Stinner5362abf2013-11-27 23:39:55 +0100401 This attribute has no effect if the traceback limit is ``1``. See the
402 :func:`get_traceback_limit` function and :attr:`Snapshot.traceback_limit`
403 attribute.
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100404
405
406Frame
Georg Brandl717e0282014-10-31 10:21:07 +0100407^^^^^
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100408
409.. class:: Frame
410
411 Frame of a traceback.
412
413 The :class:`Traceback` class is a sequence of :class:`Frame` instances.
414
415 .. attribute:: filename
416
417 Filename (``str``).
418
419 .. attribute:: lineno
420
421 Line number (``int``).
422
423
424Snapshot
Georg Brandl717e0282014-10-31 10:21:07 +0100425^^^^^^^^
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100426
427.. class:: Snapshot
428
429 Snapshot of traces of memory blocks allocated by Python.
430
431 The :func:`take_snapshot` function creates a snapshot instance.
432
433 .. method:: compare_to(old_snapshot: Snapshot, group_by: str, cumulative: bool=False)
434
435 Compute the differences with an old snapshot. Get statistics as a sorted
436 list of :class:`StatisticDiff` instances grouped by *group_by*.
437
Berker Peksag49008772014-11-10 23:15:32 +0200438 See the :meth:`Snapshot.statistics` method for *group_by* and *cumulative*
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100439 parameters.
440
441 The result is sorted from the biggest to the smallest by: absolute value
442 of :attr:`StatisticDiff.size_diff`, :attr:`StatisticDiff.size`, absolute
443 value of :attr:`StatisticDiff.count_diff`, :attr:`Statistic.count` and
444 then by :attr:`StatisticDiff.traceback`.
445
446
447 .. method:: dump(filename)
448
449 Write the snapshot into a file.
450
451 Use :meth:`load` to reload the snapshot.
452
453
454 .. method:: filter_traces(filters)
455
456 Create a new :class:`Snapshot` instance with a filtered :attr:`traces`
457 sequence, *filters* is a list of :class:`Filter` instances. If *filters*
458 is an empty list, return a new :class:`Snapshot` instance with a copy of
459 the traces.
460
461 All inclusive filters are applied at once, a trace is ignored if no
462 inclusive filters match it. A trace is ignored if at least one exclusive
463 filter matchs it.
464
465
466 .. classmethod:: load(filename)
467
468 Load a snapshot from a file.
469
470 See also :meth:`dump`.
471
472
473 .. method:: statistics(group_by: str, cumulative: bool=False)
474
475 Get statistics as a sorted list of :class:`Statistic` instances grouped
476 by *group_by*:
477
478 ===================== ========================
479 group_by description
480 ===================== ========================
481 ``'filename'`` filename
482 ``'lineno'`` filename and line number
483 ``'traceback'`` traceback
484 ===================== ========================
485
486 If *cumulative* is ``True``, cumulate size and count of memory blocks of
487 all frames of the traceback of a trace, not only the most recent frame.
488 The cumulative mode can only be used with *group_by* equals to
Victor Stinner8e3708d2013-11-26 00:45:47 +0100489 ``'filename'`` and ``'lineno'``.
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100490
491 The result is sorted from the biggest to the smallest by:
492 :attr:`Statistic.size`, :attr:`Statistic.count` and then by
493 :attr:`Statistic.traceback`.
494
495
496 .. attribute:: traceback_limit
497
498 Maximum number of frames stored in the traceback of :attr:`traces`:
499 result of the :func:`get_traceback_limit` when the snapshot was taken.
500
501 .. attribute:: traces
502
503 Traces of all memory blocks allocated by Python: sequence of
504 :class:`Trace` instances.
505
506 The sequence has an undefined order. Use the :meth:`Snapshot.statistics`
507 method to get a sorted list of statistics.
508
509
510Statistic
Georg Brandl717e0282014-10-31 10:21:07 +0100511^^^^^^^^^
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100512
513.. class:: Statistic
514
515 Statistic on memory allocations.
516
517 :func:`Snapshot.statistics` returns a list of :class:`Statistic` instances.
518
519 See also the :class:`StatisticDiff` class.
520
521 .. attribute:: count
522
523 Number of memory blocks (``int``).
524
525 .. attribute:: size
526
527 Total size of memory blocks in bytes (``int``).
528
529 .. attribute:: traceback
530
531 Traceback where the memory block was allocated, :class:`Traceback`
532 instance.
533
534
535StatisticDiff
Georg Brandl717e0282014-10-31 10:21:07 +0100536^^^^^^^^^^^^^
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100537
538.. class:: StatisticDiff
539
540 Statistic difference on memory allocations between an old and a new
541 :class:`Snapshot` instance.
542
543 :func:`Snapshot.compare_to` returns a list of :class:`StatisticDiff`
544 instances. See also the :class:`Statistic` class.
545
546 .. attribute:: count
547
548 Number of memory blocks in the new snapshot (``int``): ``0`` if
549 the memory blocks have been released in the new snapshot.
550
551 .. attribute:: count_diff
552
553 Difference of number of memory blocks between the old and the new
554 snapshots (``int``): ``0`` if the memory blocks have been allocated in
555 the new snapshot.
556
557 .. attribute:: size
558
559 Total size of memory blocks in bytes in the new snapshot (``int``):
560 ``0`` if the memory blocks have been released in the new snapshot.
561
562 .. attribute:: size_diff
563
564 Difference of total size of memory blocks in bytes between the old and
565 the new snapshots (``int``): ``0`` if the memory blocks have been
566 allocated in the new snapshot.
567
568 .. attribute:: traceback
569
570 Traceback where the memory blocks were allocated, :class:`Traceback`
571 instance.
572
573
574Trace
Georg Brandl717e0282014-10-31 10:21:07 +0100575^^^^^
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100576
577.. class:: Trace
578
579 Trace of a memory block.
580
581 The :attr:`Snapshot.traces` attribute is a sequence of :class:`Trace`
582 instances.
583
584 .. attribute:: size
585
586 Size of the memory block in bytes (``int``).
587
588 .. attribute:: traceback
589
590 Traceback where the memory block was allocated, :class:`Traceback`
591 instance.
592
593
594Traceback
Georg Brandl717e0282014-10-31 10:21:07 +0100595^^^^^^^^^
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100596
597.. class:: Traceback
598
599 Sequence of :class:`Frame` instances sorted from the most recent frame to
600 the oldest frame.
601
602 A traceback contains at least ``1`` frame. If the ``tracemalloc`` module
603 failed to get a frame, the filename ``"<unknown>"`` at line number ``0`` is
604 used.
605
606 When a snapshot is taken, tracebacks of traces are limited to
607 :func:`get_traceback_limit` frames. See the :func:`take_snapshot` function.
608
609 The :attr:`Trace.traceback` attribute is an instance of :class:`Traceback`
610 instance.
611
Victor Stinnera91ff142014-02-16 23:53:38 +0100612 .. method:: format(limit=None)
613
614 Format the traceback as a list of lines with newlines. Use the
615 :mod:`linecache` module to retrieve lines from the source code. If
616 *limit* is set, only format the *limit* most recent frames.
617
618 Similar to the :func:`traceback.format_tb` function, except that
619 :meth:`format` does not include newlines.
620
621 Example::
622
623 print("Traceback (most recent call first):")
624 for line in traceback:
625 print(line)
626
627 Output::
628
629 Traceback (most recent call first):
630 File "test.py", line 9
631 obj = Object()
632 File "test.py", line 12
633 tb = tracemalloc.get_object_traceback(f())
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100634