{"id":94002,"date":"2022-04-27T16:16:58","date_gmt":"2022-04-27T16:16:58","guid":{"rendered":"https:\/\/www.red-gate.com\/simple-talk\/?p=94002"},"modified":"2026-10-28T17:35:18","modified_gmt":"2026-10-28T17:35:18","slug":"memory-profiling-in-python-with-tracemalloc","status":"publish","type":"post","link":"https:\/\/www.red-gate.com\/simple-talk\/development\/python\/memory-profiling-in-python-with-tracemalloc\/","title":{"rendered":"Memory profiling in Python with tracemalloc"},"content":{"rendered":"<p><strong>tracemalloc is Python&#8217;s built-in module for tracing memory allocations, and the way to find a leak with it is to compare snapshots. Call tracemalloc.start(), take a snapshot before and after the code you suspect, and use snapshot.compare_to() to list the source lines whose allocated memory grew the most. Starting the tracer with more frames &#8211; tracemalloc.start(25) &#8211; lets you print a traceback showing where the leaked objects were created. This article traces a simulated leak step by step: starting the tracer, comparing snapshots, reading the statistics and following the traceback to the cause.<\/strong><\/p>\n\nMemory profiling is useful when looking at how much memory an application is using. The most important use case, however, is when you suspect that the application is leaking memory, and it is important to trace where that leak occurs in the code.\n\nA memory leak happens when a block of memory allocated by an application is not released back to the operating system, even after the object is out of scope and there are no remaining references to it. When this happens, memory utilization keeps increasing, until an OOM (out-of-memory error) occurs, and the operating system kills the application. If the utilization metric is plotted on a graph, it will display a constantly growing trend until the application dies. If the application restarts itself after the OOM, it will exhibit a sawtooth behavior, indicating the repeated increase and sudden drop at OOM. In programming languages where the compiler\/interpreter doesn\u2019t manage allocations, a leak can occur if the developer forgets to free allocated memory. It is, however, not uncommon, to see memory leaks in memory-managed languages as well.\n\nPython manages memory allocations itself. Python&#8217;s memory manager is responsible for all allocations and deallocations on the private heap. By default, Python uses reference counting to keep track of freeable objects. The optional garbage collector provides supplemental mechanisms to detect unreachable objects, otherwise not reclaimed due to cyclic referencing.\n\nSeveral tools are available for profiling memory in Python. This article covers \u201ctracemalloc\u201d which is part of the standard library. Getting started is very easy because no special installation is needed. One can start profiling and viewing the statistics straight out of the box. Tracemalloc provides statistics about objects allocated by Python on the heap. It does not account for any allocations done by underlying C libraries.\n\nThe profiler works by letting you take a snapshot of memory during runtime. There are several convenient APIs to then display the statistics contained in that snapshot, grouped by filename or lineno. It is also possible to compare two snapshots, which helps identify how memory use changes over the course of program execution. Finally, there are methods to display the traceback to where a block of memory is allocated in the code.\n\nI will go through an example that simulates constant growing memory (similar to a leak) and how to use the tracemalloc module to display statistics and eventually trace the line of code introducing that leak. For more on this, see <a href=\"https:\/\/www.red-gate.com\/simple-talk\/development\/dotnet-development\/10-reasons-python-better-than-c-sharp\/\">10 reasons Python is better than C#.<\/a> For more on this, see <a href=\"https:\/\/www.red-gate.com\/simple-talk\/development\/dotnet-development\/the-dangers-of-the-large-object-heap\/\">the dangers of the Large Object Heap in .NET.<\/a>\n<h2><a id=\"post-94002-_30j0zll\"><\/a>Tracing a memory leak<\/h2>\nHere is a one-liner function called <code>mem_leaker()<\/code> that will be used to simulate the memory leak. It grows a global array by ten thousand elements every time it is invoked.\n<pre class=\"lang:python theme:powershell-ise\">arr = []\ndef mem_leaker():\n\t'''Appends to a global array in order to simulate a memory leak.'''\n\tarr.append(np.ones(10000, dtype=np.int64))<\/pre>\nI wrapped this function inside a script named memleak.py with some driver code. The first thing to do is to call <code>tracemalloc.start()<\/code> as early as possible in order to start profiling. The default frame count is 1. This value defines the depth of a trace python will capture. The value can be overridden by setting <code>PYTHONTRACEMALLOC<\/code> environment variable to a desired number. In this example, I am passing a value of \u201c10\u201d to set the count to ten at runtime.\n\nThe tiny for loop iterates five times, invoking the make-shift memory leaker each time. The call to <code>gc.collect()<\/code> just nudges Python&#8217;s garbage collector to release any unreachable memory blocks to filter out noise. Although, you can be sure this program does not create any cyclic references.\n\nListing: memleak.py\n<pre class=\"lang:python theme:powershell-ise\">import gc\nimport tracemalloc\n\nimport numpy as np\n\nimport profiler\n\narr = []\ndef mem_leaker():\n\t'''Appends to a global array in order to simulate a memory leak.'''\n\tarr.append(np.ones(10000, dtype=np.int64))\n\n\nif __name__ == '__main__':\n\ttracemalloc.start(10)\n\n\tfor _ in range(5):\n    \t    mem_leaker()\n    \t    gc.collect()\n    \t    profiler.snapshot()\n\n\tprofiler.display_stats()\n\tprofiler.compare()\n\tprofiler.print_trace()<\/pre>\nAll the profiling code is written inside a separate script called profiler.py.\n\nListing: profiler.py\n<pre class=\"lang:python theme:powershell-ise\">import tracemalloc\n\n# list to store memory snapshots\nsnaps = []\n\ndef snapshot():\n\tsnaps.append(tracemalloc.take_snapshot())\n\n\ndef display_stats():\n\tstats = snaps[0].statistics('filename')\n\tprint(\"\\n*** top 5 stats grouped by filename ***\")\n\tfor s in stats[:5]:\n    \t    print(s)\n\n\ndef compare():\n\tfirst = snaps[0]\n\tfor snapshot in snaps[1:]:\n    \t    stats = snapshot.compare_to(first, 'lineno')\n    \t    print(\"\\n*** top 10 stats ***\")\n    \t    for s in stats[:10]:\n              print(s)\n\n\ndef print_trace():\n\t# pick the last saved snapshot, filter noise\n\tsnapshot = snaps[-1].filter_traces((\n    \t    tracemalloc.Filter(False, \"&lt;frozen importlib._bootstrap&gt;\"),\n    \t    tracemalloc.Filter(False, \"&lt;frozen importlib._bootstrap_external&gt;\"),\n    \t    tracemalloc.Filter(False, \"&lt;unknown&gt;\"),\n\t))\n\tlargest = snapshot.statistics(\"traceback\")[0]\n\n\tprint(f\"\\n*** Trace for largest memory block - ({largest.count} blocks, {largest.size\/1024} Kb) ***\")\n\tfor l in largest.traceback.format():\n    \t    print(l)<\/pre>\n&nbsp;\n\nGoing back to the for loop in the driver code, after <code>mem_leaker()<\/code> is invoked, <code>profiler.snapshot(),<\/code> which is just a wrapper around <code>tracemalloc.take_snapshot(),<\/code> will take a snapshot and store it in a list. The length of the list will be five at the end of the loop.\n\nOnce you have the snapshots, you can see how much memory was allocated. It can be useful to begin with per file grouping if the application is big, and you have no idea where the leak is happening. For demonstration, take a closer look at <code>profiler.display_stats();<\/code> it displays the first five grouped items from the first snapshot.\n<pre class=\"lang:python theme:powershell-ise\">def display_stats():\n\tstats = snaps[0].statistics('filename')\n\tprint(\"\\n*** top 5 stats grouped by filename ***\")\n\tfor s in stats[:5]:\n    \t    print(s)<\/pre>\nThe output looks like this.\n\n<img loading=\"lazy\" decoding=\"async\" class=\"alignnone wp-image-94062 size-full\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2022\/04\/memleak1.png\" alt=\"An image showing the top 5 stats grouped by file name. numpy\\core\\numeric.py size-78.2 is the top\" width=\"788\" height=\"108\" \/>\n\nAt the top of the list, numpy&#8217;s numeric.py allocated 78.2 Kb of memory. The tracemalloc module itself will also use some memory for profiling. That should be ignored during observation.\n<h2><a id=\"post-94002-_1fob9te\"><\/a>Comparing snapshots and observing trends<\/h2>\nNow, in order to debug further, The code compared the first snapshot with each subsequent snapshot to see the top ten differences using <code>compare().<\/code>\n<pre class=\"lang:python theme:powershell-ise\">def compare():\n\tfirst = snaps[0]\n\tfor snapshot in snaps[1:]:\n    \t    stats = snapshot.compare_to(first, 'lineno')\n    \t    print(\"\\n*** top 10 stats ***\")\n    \t    for s in stats[:10]:\n              print(s)<\/pre>\nThe complete output of compare() looks like this.\n\n<img loading=\"lazy\" decoding=\"async\" class=\"alignnone wp-image-94063 size-full\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2022\/04\/memleak2.png\" alt=\"A large image showing the output of each call. The important info is described in the article.\" width=\"789\" height=\"860\" \/>\n\nSince there were five total snapshots, there are four sets of statistics from the comparisons. Some important observations here:\n<ul>\n \t<li>numpy\/core\/numeric.py at line 204, is at the top in each set, allocating the most memory.<\/li>\n \t<li>Now, note the change in memory usage by numeric.py as I go over each of the result sets.<\/li>\n<\/ul>\nIn the first set, the total memory used by numeric.py is 156 Kb, an increase of 78 Kb from the first snapshot.\n\nIn the second set, total memory used by numeric.py jumps to 235 Kb, a total increase of 156 Kb from the first snapshot. Doing a little math, this also means there was an increase of ~79 Kb since the last snapshot.\n\nIn the third set, total memory used by numeric.py jumps to 313 Kb, a total increase of 235 Kb from the first snapshot. This also means there was again an increase of ~78 Kb since the last snapshot.\n\nIn the fourth set, total memory used by numeric.py jumps to 391 Kb, a total increase of 313 Kb from the first snapshot. This also means there was, once again, an increase of ~78 Kb since the last snapshot.\n<ul>\n \t<li>A clear cumulative trend can be seen here in the allocation done by numeric.py. At each iteration, ignoring rounding differences, ~78 Kb more memory was allocated. If you look at <code>mem_leaker()<\/code> again, it appends ten thousand elements to the array, each of size 8 bytes, which brings the total to 80000 bytes, or 78.125 Kb. This matches the observed increase from the snapshot deltas.<\/li>\n \t<li>It is constantly growing trends like this that eventually lead to a code problem if the growth pattern is unexpected.<\/li>\n<\/ul>\n<h2><a id=\"post-94002-_3znysh7\"><\/a>See a traceback<\/h2>\nThe last thing in the example was to print the traceback for the largest memory block for more granularity. In this case, the largest block is one from numeric.py. The <code>filter_traces()<\/code> method is very helpful in eliminating noise when debugging long traces.\n<pre class=\"lang:python theme:powershell-ise\">def print_trace():\n\t# pick the last saved snapshot, filter noise\n\tsnapshot = snaps[-1].filter_traces((\n    \t    tracemalloc.Filter(False, \"&lt;frozen importlib._bootstrap&gt;\"),\n    \t    tracemalloc.Filter(False, \"&lt;frozen importlib._bootstrap_external&gt;\"),\n    \t    tracemalloc.Filter(False, \"&lt;unknown&gt;\"),\n\t))\n\tlargest = snapshot.statistics(\"traceback\")[0]\n\n\tprint(f\"\\n*** Trace for largest memory block - ({largest.count} blocks, {largest.size\/1024} Kb) ***\")\n\tfor l in largest.traceback.format():\n    \t    print(l)<\/pre>\nThe trace looks like this.\n\n<img loading=\"lazy\" decoding=\"async\" class=\"alignnone wp-image-94064 size-full\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/2022\/04\/memleak3.png\" alt=\"Image showing Trace for largest memory block - (10 blocks, 391.0546875 kb) then shows line in the memleak.py file 18, 11, 203\" width=\"753\" height=\"130\" \/>\n\nThis trace leads from the application code to the line in the numpy library, where the allocation actually takes place. You can look at the source code here &#8211; <a href=\"https:\/\/github.com\/numpy\/numpy\/blob\/main\/numpy\/core\/numeric.py#L204\">https:\/\/github.com\/numpy\/numpy\/blob\/main\/numpy\/core\/numeric.py#L204<\/a>.<a id=\"post-94002-_2et92p0\"><\/a>\n<h2>Conclusion<\/h2>\nHere, you saw a simple demonstration of using Python stdlib&#8217;s tracemalloc module to observe various memory related statistics, compared snapshots to see the allocation deltas and used all this information to trace back to the code using a substantial amount of memory. In large applications, it may take some time to narrow down scope and find the line of code introducing a leak. The tracemalloc module provides all the necessary APIs to do so, and it just works out of the box.<a id=\"post-94002-_tyjcwt\"><\/a>\n<h2>References<\/h2>\n<a href=\"https:\/\/docs.python.org\/3\/library\/tracemalloc.html\">https:\/\/docs.python.org\/3\/library\/tracemalloc.html<\/a>\n\n\n<section id=\"faq\" class=\"faq-block my-5xl\">\n    <h2>FAQs<\/h2>\n\n            <h3 class=\"mt-4xl\">1. How do I track down a memory leak in Python with tracemalloc?<\/h3>\n        <div class=\"faq-answer\">\n            <p>Start tracing early with tracemalloc.start(), take a snapshot with tracemalloc.take_snapshot() before the suspect code and another after it has run several times, then call second.compare_to(first, &#8216;lineno&#8217;) and print the top entries: the lines whose size keeps growing are where the leak allocates. Use &#8216;traceback&#8217; instead of &#8216;lineno&#8217;, with more frames enabled, to see the call path that created the objects.<\/p>\n        <\/div>\n            <h3 class=\"mt-4xl\">2. Does tracemalloc slow down a Python program?<\/h3>\n        <div class=\"faq-answer\">\n            <p>Yes. It hooks every allocation, so it adds CPU time and memory of its own, and the cost rises with the number of frames you ask it to record. Use it in a test or staging run that reproduces the leak rather than leaving it on in production.<\/p>\n        <\/div>\n    <\/section>\n","protected":false},"excerpt":{"rendered":"<p>You can find memory leaks in Python code with tracemalloc. In this article, Priyanka Nawalramka demonstrates how to use tracemalloc to find the leaks.&hellip;<\/p>\n","protected":false},"author":339453,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[53,146042],"tags":[95506],"coauthors":[145947],"class_list":["post-94002","post","type-post","status-publish","format-standard","hentry","category-featured","category-python","tag-automate"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/94002","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/users\/339453"}],"replies":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/comments?post=94002"}],"version-history":[{"count":15,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/94002\/revisions"}],"predecessor-version":[{"id":114240,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/94002\/revisions\/114240"}],"wp:attachment":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/media?parent=94002"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/categories?post=94002"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/tags?post=94002"},{"taxonomy":"author","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/coauthors?post=94002"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}