Skip to content

Instantly share code, notes, and snippets.

@pydemo
Last active September 14, 2018 18:46
Show Gist options
  • Select an option

  • Save pydemo/ca002ecd38897b9e8b8fcc21ff6ede43 to your computer and use it in GitHub Desktop.

Select an option

Save pydemo/ca002ecd38897b9e8b8fcc21ff6ede43 to your computer and use it in GitHub Desktop.
Using memory_profiler in Python
@profile
def benchmark_memory():
sum=0
a=[]
for n in list(range(100000)):
sum +=1
a.append(n)
if __name__ == '__main__':
benchmark_memory()
def benchmark_memory():
sum=0
a=[]
for n in list(range(100000)):
sum +=1
a.append(n)
if __name__ == '__main__':
benchmark_memory()

Create profile

mprof run mem_profiled.py

Plot profile

mprof plot

Opens plotted profile

Install

pip -m install memory_profiler

iPython setup

from memrun import benchmark_memory
%load_ext memory_profiler
%mprun -f benchmark_memory  benchmark_memory()

Result

Filename: memrun.py

Line #    Mem usage    Increment   Line Contents
================================================
     3     30.0 MiB     30.0 MiB   def benchmark_memory():
     4     30.0 MiB      0.0 MiB        sum=0
     5     30.0 MiB      0.0 MiB        a=[]
     6     32.3 MiB      1.5 MiB        for n in list(range(100000)):
     7     32.3 MiB      0.1 MiB                sum +=1
     8     32.3 MiB      0.8 MiB                a.append(n)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment