Python memory_profiler
last modified November 30, 2026 Python 3.15
In this article we show how to measure the memory usage of Python code
with the memory_profiler library.
The library samples the resident set size (RSS) of a process:
the amount of physical memory the operating system has given to it. It
can report the memory of a running process, the peak memory of a single
function call, and the change in memory after each line of a function.
The mprof command records memory over the whole run of a
program and plots it.
The project is no longer actively maintained; the last release, 0.61.0,
dates from 2022. It still works with Python 3.15, as the examples show,
but it uses an asyncio function that is scheduled for
removal in Python 3.16. For new code that needs to know which
objects use memory, the standard tracemalloc module is
the long-term choice; we compare the two at the end of the article.
$ pip install memory_profiler
Memory of the current process
The memory_usage function returns a list of memory samples
in MiB. With -1 as the first argument, it samples the
current process.
from memory_profiler import memory_usage
if __name__ == '__main__':
print(memory_usage(-1, interval=0.1, timeout=0.3))
data = list(range(5_000_000))
print(memory_usage(-1, interval=0.1, timeout=0.3))
print(len(data))
The interval argument sets the time between samples and
timeout the length of the measurement, so we get three
samples each time. After we create a list of five million integers, the
process uses about 190 MiB more.
The memory_usage function starts a helper process to take
the samples. Since Python 3.14, new processes on Linux are started with
the forkserver method, which imports the main module again
in the child. Without the if __name__ == '__main__': guard,
the child would run the measurement again and fail with a
RuntimeError. See
Python multiprocessing for
details.
$ python current_usage.py [23.94140625, 23.94140625, 23.94140625] [215.25, 215.25, 215.25] 5000000
Peak memory of a function
When memory_usage receives a tuple of a function, its
positional arguments, and optionally its keyword arguments, it calls
the function and samples memory while it runs.
from memory_profiler import memory_usage
def build_squares(n):
squares = [i * i for i in range(n)]
return sum(squares)
def sum_squares(n):
return sum(i * i for i in range(n))
if __name__ == '__main__':
base = memory_usage(-1, timeout=0.1)[0]
for func in (build_squares, sum_squares):
peak, total = memory_usage((func, (5_000_000,)), interval=0.01,
max_usage=True, retval=True)
print(f'{func.__name__}: peak {peak - base:.1f} MiB over base, '
f'result {total}')
Both functions compute the same sum of squares. The first builds a list
of five million squares and then sums it; the second sums the values of
a generator expression one by one. With max_usage=True, we
get only the highest sample instead of the whole list, and
retval=True also returns the function's result. We subtract
the memory of the process before the call to see how much the call
itself needed.
$ python function_usage.py build_squares: peak 193.0 MiB over base, result 41666654166667500000 sum_squares: peak 3.9 MiB over base, result 41666654166667500000
Line-by-line profile
The @profile decorator reports how memory changes after
each line of a function. When the program runs through the
memory_profiler module, the decorator is available as a
built-in name and does not have to be imported.
@profile
def load_words(n):
words = ['falcon', 'sky', 'cloud'] * n
upper = list(map(str.upper, words))
joined = ' '.join(upper)
del upper
return len(joined)
load_words(1_000_000)
The function builds a list of three million strings, an uppercase copy of the list, and one long joined string. Then it deletes the uppercase copy.
In the report, Mem usage is the memory of the process after the
line, Increment is the change caused by the line, and
Occurrences is the number of times the line ran. The
del upper line frees almost 160 MiB, the memory taken by
the three million new strings. The first line shows the memory of the
process when the function was entered.
The run also prints a DeprecationWarning: the library calls
asyncio.iscoroutinefunction, which Python 3.16 removes. It
is harmless in Python 3.15 and is shown here only because the library
runs as the main module.
$ python -m memory_profiler line_profile.py
/home/user/venv/lib/python3.15/site-packages/memory_profiler.py:752: DeprecationWarning: 'asyncio.iscoroutinefunction' is deprecated and slated for removal in Python 3.16; use inspect.iscoroutinefunction() instead
if iscoroutinefunction(func):
Filename: line_profile.py
Line # Mem usage Increment Occurrences Line Contents
=============================================================
1 24.797 MiB 24.797 MiB 1 @profile
2 def load_words(n):
3 47.688 MiB 22.891 MiB 1 words = ['falcon', 'sky', 'cloud'] * n
4 208.785 MiB 161.098 MiB 1 upper = list(map(str.upper, words))
5 225.004 MiB 16.219 MiB 1 joined = ' '.join(upper)
6 65.051 MiB -159.953 MiB 1 del upper
7 65.051 MiB 0.000 MiB 1 return len(joined)
Importing the decorator
The profile decorator can also be imported from
memory_profiler. The program then runs as usual and prints
the report each time a decorated function returns.
from memory_profiler import profile
@profile(precision=1)
def read_rows(n):
rows = [(i, f'user{i}', i % 100) for i in range(n)]
total = sum(age for _, _, age in rows)
return total / n
@profile(precision=1)
def read_columns(n):
ids = list(range(n))
names = [f'user{i}' for i in ids]
ages = [i % 100 for i in ids]
return sum(ages) / n
if __name__ == '__main__':
print(read_rows(500_000))
print(read_columns(500_000))
The two functions store the same data in two ways: as a list of
tuples, and as three separate lists. The precision
argument sets the number of decimal places in the report.
In the report, a list comprehension is counted once for each item plus
once at the start; since Python 3.12 comprehensions run inline in the
function, so the profiler sees every iteration. Storing columns needs
less memory than storing rows, because there are no tuple objects and
the small integers in ages are shared, cached objects.
Each run of a line adds tracing overhead; a comprehension over millions
of items becomes very slow under the profiler. It is better to profile
with a smaller input or to replace comprehensions with
map calls, as we did in the previous example.
$ python import_profile.py
Filename: /home/user/python/import_profile.py
Line # Mem usage Increment Occurrences Line Contents
=============================================================
3 24.2 MiB 24.2 MiB 1 @profile(precision=1)
4 def read_rows(n):
5 112.6 MiB 88.4 MiB 500001 rows = [(i, f'user{i}', i % 100) for i in range(n)]
6 113.5 MiB 0.9 MiB 1000003 total = sum(age for _, _, age in rows)
7 113.5 MiB 0.0 MiB 1 return total / n
49.5
Filename: /home/user/python/import_profile.py
Line # Mem usage Increment Occurrences Line Contents
=============================================================
9 29.3 MiB 29.3 MiB 1 @profile(precision=1)
10 def read_columns(n):
11 43.7 MiB 14.3 MiB 1 ids = list(range(n))
12 78.1 MiB 34.4 MiB 500001 names = [f'user{i}' for i in ids]
13 81.9 MiB 3.8 MiB 500001 ages = [i % 100 for i in ids]
14 81.9 MiB 0.0 MiB 1 return sum(ages) / n
49.5
A growing cache
A common source of memory problems in long-running programs is a cache that never forgets anything. We sample the memory of the process after each batch of requests to see the trend.
from memory_profiler import memory_usage
cache = {}
def render_page(page_id):
if page_id not in cache:
cache[page_id] = f'<html>page {page_id}</html>' * 500
return cache[page_id]
def serve(requests):
for page_id in requests:
render_page(page_id)
if __name__ == '__main__':
print(f'start: {memory_usage(-1, timeout=0.1)[0]:.1f} MiB')
for batch in range(4):
start = batch * 5_000
serve(range(start, start + 5_000))
used = memory_usage(-1, timeout=0.1)[0]
print(f'batch {batch}: {len(cache)} pages, {used:.1f} MiB')
cache.clear()
print(f'cleared: {memory_usage(-1, timeout=0.1)[0]:.1f} MiB')
The render_page function stores every page it renders in a
global dictionary. Each batch serves 5,000 new pages, and the process
grows by more than 50 MiB per batch. Memory goes back down only when
the cache is cleared. Steady growth over repeated batches of the same
work is the typical sign of such a leak.
$ python growing_cache.py start: 24.0 MiB batch 0: 5000 pages, 76.4 MiB batch 1: 10000 pages, 129.4 MiB batch 2: 15000 pages, 185.0 MiB batch 3: 20000 pages, 240.2 MiB cleared: 26.3 MiB
A bounded cache
The fix is to limit the size of the cache. The
functools.lru_cache decorator keeps only the most recently
used results.
from functools import lru_cache
from memory_profiler import memory_usage
@lru_cache(maxsize=2_000)
def render_page(page_id):
return f'<html>page {page_id}</html>' * 500
def serve(requests):
for page_id in requests:
render_page(page_id)
if __name__ == '__main__':
print(f'start: {memory_usage(-1, timeout=0.1)[0]:.1f} MiB')
for batch in range(4):
start = batch * 5_000
serve(range(start, start + 5_000))
info = render_page.cache_info()
used = memory_usage(-1, timeout=0.1)[0]
print(f'batch {batch}: {info.currsize} pages, {used:.1f} MiB')
With maxsize=2_000, the cache drops the least recently used
pages when it is full. The cache_info method reports the
current size of the cache, and the memory of the process stays almost
flat no matter how many batches we serve.
$ python bounded_cache.py start: 24.1 MiB batch 0: 2000 pages, 45.4 MiB batch 1: 2000 pages, 45.5 MiB batch 2: 2000 pages, 46.5 MiB batch 3: 2000 pages, 46.5 MiB
Memory over time with mprof
The mprof command, installed together with the library,
records the memory of a whole program run. The program below loads
five batches of records, drops them, and then loads one larger batch.
import time
def load(n):
return [f'record {i}' * 10 for i in range(n)]
def main():
batches = []
for _ in range(5):
batches.append(load(200_000))
time.sleep(0.3)
batches.clear()
time.sleep(0.5)
data = load(400_000)
time.sleep(0.5)
return len(data)
if __name__ == '__main__':
print(main())
The short sleeps between the steps make the stages visible in the
recording. The mprof run command starts the program and
samples its memory every 0.1 seconds. The samples are stored in a
mprofile_*.dat file in the current directory.
$ mprof run timeline.py mprof: Sampling memory every 0.1s running new process running as a Python program... 400000
Peak of a recording
The mprof peak command prints the highest sample of the last
recording, together with the name of its data file.
$ mprof peak Using last profile data. mprofile_20261130193906.dat 201.250 MiB
Plotting a recording
The mprof plot command draws the last recording with
Matplotlib. The -o option saves the chart to a file
instead of opening a window, and --title sets its title.
The chart shows the memory of the process over time. The memory grows by about 35 MiB with each batch; the dashed lines mark the peak. After the batches are cleared, the process drops to the starting level, and the last load raises it again. The command itself prints only which recording it used.
$ mprof plot -o timeline.png --title timeline.py Using last profile data.
RSS versus tracemalloc
The memory_profiler library measures the RSS of the
process, which is what the operating system sees. The standard
tracemalloc module counts the memory that Python allocates
for objects. The two numbers answer different questions, as the next
example shows.
import tracemalloc
from memory_profiler import memory_usage
def rss():
return memory_usage(-1, timeout=0.1)[0]
if __name__ == '__main__':
tracemalloc.start()
print(f'start: rss {rss():6.1f} MiB')
data = [str(i) * 20 for i in range(1_000_000)]
traced, peak = tracemalloc.get_traced_memory()
print(f'allocated: rss {rss():6.1f} MiB, traced {traced / 2**20:5.1f} MiB')
del data[::2]
traced, peak = tracemalloc.get_traced_memory()
print(f'half gone: rss {rss():6.1f} MiB, traced {traced / 2**20:5.1f} MiB')
del data
traced, peak = tracemalloc.get_traced_memory()
print(f'all gone: rss {rss():6.1f} MiB, traced {traced / 2**20:5.1f} MiB')
print(f'peak traced: {peak / 2**20:.1f} MiB')
We create a million strings, delete every second one, and finally
delete the whole list. The get_traced_memory function
returns the current and the peak size of the traced memory.
After half of the strings are deleted, the traced memory halves, but the
RSS does not move: the freed memory is scattered across memory blocks
that still hold live strings, so Python cannot return it to the
operating system. Only after all strings are gone does the RSS fall,
and even then not to the starting value. The RSS is also higher than
the traced memory, partly because tracemalloc itself needs
memory to store a trace for every allocation.
Use memory_profiler to see how much memory a program really
costs the system and when it grows; use tracemalloc to
find out which lines of code allocated the objects.
$ python rss_tracemalloc.py start: rss 25.1 MiB allocated: rss 291.3 MiB, traced 159.5 MiB half gone: rss 291.8 MiB, traced 80.0 MiB all gone: rss 107.2 MiB, traced 0.0 MiB peak traced: 163.3 MiB
Source
memory_profiler on GitHub, tracemalloc — Trace memory allocations
In this article we have measured the memory of a process and of a
function call with memory_usage, profiled functions line
by line with @profile, found and fixed a growing cache,
recorded and plotted memory over time with mprof, and
compared RSS with tracemalloc. To measure time instead of
memory, see Python timeit; the
Python psutil article shows how to read
the memory of other processes.
Author
List all Python tutorials.