Monitoring Memory Usage of a Running Python Program
Last Updated :
18 Sep, 2024
Managing memory is important in any programming logic but this becomes necessary for Python as Python is used in Ml and AI where vast data needs to be managed. Memory leaks, i.e., the program is out of memory after running for several hours. To manage these memory leaks memory monitoring is essential. Monitoring memory is also called profiling. As a developer, it's a necessity that we profile our program and use less memory allocation as much as possible.
Monitoring Memory Usage Using Tracemalloc
Tracemalloc is a library module that traces every memory block in Python. The tracing starts by using the start() during runtime. This library module can also give information about the total size, number, and average size of allocated memory blocks.
Example
The output is given in form of (current, peak), i.e., current memory is the memory the code is currently using,uses and peak memory is the maximum space the program used while executing.
Python
# importing the module
import tracemalloc
# code or function for which memory
# has to be monitored
def app():
lt = []
for i in range(0, 100000):
lt.append(i)
# starting the monitoring
tracemalloc.start()
# function call
app()
# displaying the memory
print(tracemalloc.get_traced_memory())
# stopping the library
tracemalloc.stop()
Output
(0,3617252)
Monitoring Memory Usage Using Psutil
Psutil is a python system library used to keep track of various resources in the system and their utilization. The library is used for profiling, limiting, and management of process resources. In order to install this do the following-
sudo pip install psutil [Linux]
pip install psutil [Windows]
Example
Here, All you have to do is add the decorator function and the process_memory function in your code and this will give you the memory consumed by the code and it's before and after.
Python
# importing libraries
import os
import psutil
# inner psutil function
def process_memory():
process = psutil.Process(os.getpid())
mem_info = process.memory_info()
return mem_info.rss
# decorator function
def profile(func):
def wrapper(*args, **kwargs):
mem_before = process_memory()
result = func(*args, **kwargs)
mem_after = process_memory()
print("{}:consumed memory: {:,}".format(
func.__name__,
mem_before, mem_after, mem_after - mem_before))
return result
return wrapper
# instantiation of decorator function
@profile
# main code for which
# memory has to be monitored
def func():
x = [1] * (10 ** 7)
y = [2] * (4 * 10 ** 8)
del x
return y
func()
Output:
func: consumed memory: 307,261,440
Monitoring Memory Usage Using Memory Profiler
Memory profiler from PyPI is a python library module used for monitoring process memory. It uses psutil code to create a decorator and then uses it to get the memory distribution. With this pypi module by importing one can save lines and directly call the decorator. To install use the following-
pip install -U memory_profiler
Example
This displays the memory consumed by each line in the code. Implementation of finding the memory consumption is very easy using a memory profiler as we directly call the decorator instead of writing a whole new code.
Python
# importing the library
from memory_profiler import profile
# instantiating the decorator
@profile
# code for which memory has to
# be monitored
def my_func():
x = [x for x in range(0, 1000)]
y = [y*100 for y in range(0, 1500)]
del x
return y
if __name__ == '__main__':
my_func()
Output:
Line # Mem usage Increment Occurrences Line Contents
============================================================
2 30.5 MiB 30.5 MiB 1 @profile
3 def my_func():
4 30.6 MiB 0.1 MiB 1003 x = [x for x in range(0,1000)]
5 30.7 MiB 0.1 MiB 1503 y = [y*100 for y in range(0,1500)]
6 30.7 MiB 0.0 MiB 1 del x
7 30.7 MiB 0.0 MiB 1 return y
Similar Reads
Running Python program in the background Let us see how to run a Python program or project in the background i.e. the program will start running from the moment device is on and stop at shut down or when you close it. Just run one time to assure the program is error-bug free One way is to use pythonw, pythonw is the concatenation of python
3 min read
Understanding the Execution of Python Program This article aims at providing a detailed insight into the execution of the Python program. Let's consider the below example. Example: Python3 a = 10 b = 10 print("Sum ", (a+b)) Output: Sum 20 Suppose the above python program is saved as first.py. Here first is the name and .py is the exte
2 min read
Measure time taken by program to execute in Python Measuring the execution time of a Python program is useful for performance analysis, benchmarking, and optimization. Python provides several built-in modules to achieve this with ease. In this article, we'll explore different ways to measure how long a Python program takes to run.Using the time Modu
2 min read
Python Event-Driven Programming Event-driven programming is a powerful paradigm used in Python for building responsive and scalable applications. In this model, the flow of the program is driven by events such as user actions, system notifications, or messages from other parts of the program. In this article, we will learn about e
3 min read
How To Detect File Changes Using Python In the digital age, monitoring file changes is essential for various applications, ranging from data synchronization to security. Python offers robust libraries and methods to detect file modifications efficiently. In this article, we will see some generally used method which is used to detect chang
3 min read
Create a Log File in Python Logging is an essential aspect of software development, allowing developers to track and analyze the behavior of their programs. In Python, creating log files is a common practice to capture valuable information during runtime. Log files provide a detailed record of events, errors, and other relevan
3 min read