Being a Programmer, one of the most important task is to analyse the code and optimize it , so that code should use less memory and time. One may think, finding a part of code which is taking up more space in memory is tedious task. But wait, fortunately in Python, we have different libraries for performance analysis, example: cProfile, line-profiler, guppy, memory-profiler. In this article, we’ll discuss memory-profiler library for monitoring memory consumption.
Module memory-profiler returns line-by-line analysis of memory consumption for python programs.
Installation
pip install -U memory_profiler
To get the line-by-line analysis follow below two steps:
In below example, we are calling my_func(), in which we are just did some calculation and stored in variable ‘a’ , and after that we deleted ‘a’. This program may not be related to real-world problem, but this code is enough to understand memory profiling.
from memory_profiler import profile
@profile
def my_func(x):
a = [x]*(10**8)
del a
my_func(20)
Output:
Line ## Mem usage Increment Occurences Line Contents
============================================================
2 20.3 MiB 20.3 MiB 1 @profile
3 def my_func(x):
4 783.2 MiB 762.9 MiB 1 a = [x]*(10**8)
5 20.3 MiB -762.9 MiB 1 del a
#python #performance-analysis #optimization-techniques