Creating high-performing and efficient apps requires optimizing memory utilization in the present software development environment. Memory profiling is an efficient technique for accomplishing this. Memory profiling examines a program’s memory usage and finds memory-intensive code segments, possible memory leaks, and optimization possibilities. This procedure aids programmers in making sure their apps utilize memory effectively, resulting in quicker and more scalable processes. This article is an introductory guide for memory profiling in Python.
Memory profiling is the technique of examining software to determine how much memory it utilizes. It helps identify memory-intensive code segments, potential memory leaks, and potential optimization targets. By profiling memory, developers may ensure that their applications use memory efficiently and achieve faster and more scalable operations.
Several tools are available for Python memory profiling, each with unique capabilities and applications. We look at a few of the more well-known ones here.
One common tool for tracking memory consumption is memory_profiler. It provides line-by-line information on memory use. Thus simplifying the identification of memory-intensive portions of the code.
pip install memory-profiler
To use memory_profiler
, decorate the function you want to profile with @profile
And run the script with the -m memory_profiler Flag.
from memory_profiler import profile
@profile
def my_function():
a = [1] * (10**6)
b = [2] * (2 * 10**7)
del b
return a
if __name__ == "__main__":
my_function()
Output
Running this script will produce a detailed memory usage report for each line in the decorated function.
guppy3 is a comprehensive Python programming environment with a heap analysis toolset. It includes a heap analysis tool for finding memory leaks and analyzing memory usage.
pip install guppy3
from guppy import hpy
hp = hpy()
heap = hp.heap()
print(heap)
Output
tracemalloc is a built-in module in Python that tracks memory allocations. It provides statistical memory usage analysis. Additionally, it can be useful for tracking memory leaks.
import tracemalloc
tracemalloc.start()
# Your code here (replace with actual code whose memory usage you want to monitor)
# For example, creating a large list:
data = [x ** 2 for x in range(100000)]
snapshot1 = tracemalloc.take_snapshot()
# Your code here (replace with actual code whose memory usage you want to monitor)
# For example, modifying the list:
data = [x ** 3 for x in range(100000)]
snapshot2 = tracemalloc.take_snapshot()
top_stats = snapshot2.compare_to(snapshot1, 'lineno')
for stat in top_stats[:10]:
print(stat)
Output
objgraph is a module that lets you visually explore Python object graphs. It can help find memory leaks by identifying objects that are taking up memory. Furthermore, it can help in tracking down why they are not being garbage collected.
pip install objgraph
import objgraph
# Your code here
# For example,
# Define a sample class
class MyClass:
def __init__(self, value):
self.value = value
# Create instances of the class
obj1 = MyClass(10)
obj2 = MyClass(20)
obj3 = MyClass(30)
# Assign one of the objects to a variable for inspection
some_object = obj1
objgraph.show_most_common_types()
objgraph.show_backrefs([some_object], max_depth=10)
Output
pympler is another powerful tool for tracking memory usage in Python programs. It provides detailed reports, and moreover, it can help analyze the lifetime of Python objects.
pip install pympler
from pympler import summary, muppy
all_objects = muppy.get_objects()
sum1 = summary.summarize(all_objects)
summary.print_(sum1)
Output
Also Read: Generate Reports Using Pandas Profiling
Therefore, memory profiling is essential for developing efficient and robust Python applications. By using tools like memory_profiler, guppy3, tracemalloc, objgraph, and pympler, developers can learn about their applications’ memory consumption patterns and adjust them accordingly. Frequent memory profiling enhances efficiency, guards against memory leaks, and guarantees that apps function properly.
If you want to learn more about Python, do Analytics Vidhya’s Python course.