blob: 13c81a7fedcb48e7d53ce761981d0f3d158fc1f5 [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
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
Brett Cannonf299abd2015-04-13 14:21:02 -0400366 *filename_pattern*. The ``'.pyc'`` file extension is
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100367 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
Brett Cannonf299abd2015-04-13 14:21:02 -0400377
378 .. versionchanged:: 3.5
379 The ``'.pyo'`` file extension is no longer replaced with ``'.py'``.
380
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100381 .. attribute:: inclusive
382
383 If *inclusive* is ``True`` (include), only trace memory blocks allocated
384 in a file with a name matching :attr:`filename_pattern` at line number
385 :attr:`lineno`.
386
387 If *inclusive* is ``False`` (exclude), ignore memory blocks allocated in
388 a file with a name matching :attr:`filename_pattern` at line number
389 :attr:`lineno`.
390
391 .. attribute:: lineno
392
393 Line number (``int``) of the filter. If *lineno* is ``None``, the filter
394 matches any line number.
395
396 .. attribute:: filename_pattern
397
398 Filename pattern of the filter (``str``).
399
400 .. attribute:: all_frames
401
402 If *all_frames* is ``True``, all frames of the traceback are checked. If
403 *all_frames* is ``False``, only the most recent frame is checked.
404
Victor Stinner5362abf2013-11-27 23:39:55 +0100405 This attribute has no effect if the traceback limit is ``1``. See the
406 :func:`get_traceback_limit` function and :attr:`Snapshot.traceback_limit`
407 attribute.
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100408
409
410Frame
Georg Brandl717e0282014-10-31 10:21:07 +0100411^^^^^
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100412
413.. class:: Frame
414
415 Frame of a traceback.
416
417 The :class:`Traceback` class is a sequence of :class:`Frame` instances.
418
419 .. attribute:: filename
420
421 Filename (``str``).
422
423 .. attribute:: lineno
424
425 Line number (``int``).
426
427
428Snapshot
Georg Brandl717e0282014-10-31 10:21:07 +0100429^^^^^^^^
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100430
431.. class:: Snapshot
432
433 Snapshot of traces of memory blocks allocated by Python.
434
435 The :func:`take_snapshot` function creates a snapshot instance.
436
437 .. method:: compare_to(old_snapshot: Snapshot, group_by: str, cumulative: bool=False)
438
439 Compute the differences with an old snapshot. Get statistics as a sorted
440 list of :class:`StatisticDiff` instances grouped by *group_by*.
441
Berker Peksag49008772014-11-10 23:15:32 +0200442 See the :meth:`Snapshot.statistics` method for *group_by* and *cumulative*
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100443 parameters.
444
445 The result is sorted from the biggest to the smallest by: absolute value
446 of :attr:`StatisticDiff.size_diff`, :attr:`StatisticDiff.size`, absolute
447 value of :attr:`StatisticDiff.count_diff`, :attr:`Statistic.count` and
448 then by :attr:`StatisticDiff.traceback`.
449
450
451 .. method:: dump(filename)
452
453 Write the snapshot into a file.
454
455 Use :meth:`load` to reload the snapshot.
456
457
458 .. method:: filter_traces(filters)
459
460 Create a new :class:`Snapshot` instance with a filtered :attr:`traces`
461 sequence, *filters* is a list of :class:`Filter` instances. If *filters*
462 is an empty list, return a new :class:`Snapshot` instance with a copy of
463 the traces.
464
465 All inclusive filters are applied at once, a trace is ignored if no
466 inclusive filters match it. A trace is ignored if at least one exclusive
467 filter matchs it.
468
469
470 .. classmethod:: load(filename)
471
472 Load a snapshot from a file.
473
474 See also :meth:`dump`.
475
476
477 .. method:: statistics(group_by: str, cumulative: bool=False)
478
479 Get statistics as a sorted list of :class:`Statistic` instances grouped
480 by *group_by*:
481
482 ===================== ========================
483 group_by description
484 ===================== ========================
485 ``'filename'`` filename
486 ``'lineno'`` filename and line number
487 ``'traceback'`` traceback
488 ===================== ========================
489
490 If *cumulative* is ``True``, cumulate size and count of memory blocks of
491 all frames of the traceback of a trace, not only the most recent frame.
492 The cumulative mode can only be used with *group_by* equals to
Victor Stinner8e3708d2013-11-26 00:45:47 +0100493 ``'filename'`` and ``'lineno'``.
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100494
495 The result is sorted from the biggest to the smallest by:
496 :attr:`Statistic.size`, :attr:`Statistic.count` and then by
497 :attr:`Statistic.traceback`.
498
499
500 .. attribute:: traceback_limit
501
502 Maximum number of frames stored in the traceback of :attr:`traces`:
503 result of the :func:`get_traceback_limit` when the snapshot was taken.
504
505 .. attribute:: traces
506
507 Traces of all memory blocks allocated by Python: sequence of
508 :class:`Trace` instances.
509
510 The sequence has an undefined order. Use the :meth:`Snapshot.statistics`
511 method to get a sorted list of statistics.
512
513
514Statistic
Georg Brandl717e0282014-10-31 10:21:07 +0100515^^^^^^^^^
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100516
517.. class:: Statistic
518
519 Statistic on memory allocations.
520
521 :func:`Snapshot.statistics` returns a list of :class:`Statistic` instances.
522
523 See also the :class:`StatisticDiff` class.
524
525 .. attribute:: count
526
527 Number of memory blocks (``int``).
528
529 .. attribute:: size
530
531 Total size of memory blocks in bytes (``int``).
532
533 .. attribute:: traceback
534
535 Traceback where the memory block was allocated, :class:`Traceback`
536 instance.
537
538
539StatisticDiff
Georg Brandl717e0282014-10-31 10:21:07 +0100540^^^^^^^^^^^^^
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100541
542.. class:: StatisticDiff
543
544 Statistic difference on memory allocations between an old and a new
545 :class:`Snapshot` instance.
546
547 :func:`Snapshot.compare_to` returns a list of :class:`StatisticDiff`
548 instances. See also the :class:`Statistic` class.
549
550 .. attribute:: count
551
552 Number of memory blocks in the new snapshot (``int``): ``0`` if
553 the memory blocks have been released in the new snapshot.
554
555 .. attribute:: count_diff
556
557 Difference of number of memory blocks between the old and the new
558 snapshots (``int``): ``0`` if the memory blocks have been allocated in
559 the new snapshot.
560
561 .. attribute:: size
562
563 Total size of memory blocks in bytes in the new snapshot (``int``):
564 ``0`` if the memory blocks have been released in the new snapshot.
565
566 .. attribute:: size_diff
567
568 Difference of total size of memory blocks in bytes between the old and
569 the new snapshots (``int``): ``0`` if the memory blocks have been
570 allocated in the new snapshot.
571
572 .. attribute:: traceback
573
574 Traceback where the memory blocks were allocated, :class:`Traceback`
575 instance.
576
577
578Trace
Georg Brandl717e0282014-10-31 10:21:07 +0100579^^^^^
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100580
581.. class:: Trace
582
583 Trace of a memory block.
584
585 The :attr:`Snapshot.traces` attribute is a sequence of :class:`Trace`
586 instances.
587
588 .. attribute:: size
589
590 Size of the memory block in bytes (``int``).
591
592 .. attribute:: traceback
593
594 Traceback where the memory block was allocated, :class:`Traceback`
595 instance.
596
597
598Traceback
Georg Brandl717e0282014-10-31 10:21:07 +0100599^^^^^^^^^
Victor Stinnered3b0bc2013-11-23 12:27:24 +0100600
601.. class:: Traceback
602
603 Sequence of :class:`Frame` instances sorted from the most recent frame to
604 the oldest frame.
605
606 A traceback contains at least ``1`` frame. If the ``tracemalloc`` module
607 failed to get a frame, the filename ``"<unknown>"`` at line number ``0`` is
608 used.
609
610 When a snapshot is taken, tracebacks of traces are limited to
611 :func:`get_traceback_limit` frames. See the :func:`take_snapshot` function.
612
613 The :attr:`Trace.traceback` attribute is an instance of :class:`Traceback`
614 instance.
615
Victor Stinner23f628d2014-02-16 23:53:38 +0100616 .. method:: format(limit=None)
617
618 Format the traceback as a list of lines with newlines. Use the
619 :mod:`linecache` module to retrieve lines from the source code. If
620 *limit* is set, only format the *limit* most recent frames.
621
622 Similar to the :func:`traceback.format_tb` function, except that
623 :meth:`format` does not include newlines.
624
625 Example::
626
627 print("Traceback (most recent call first):")
628 for line in traceback:
629 print(line)
630
631 Output::
632
633 Traceback (most recent call first):
634 File "test.py", line 9
635 obj = Object()
636 File "test.py", line 12
637 tb = tracemalloc.get_object_traceback(f())