How to Check Memory Usage in Python: Simple Methods
To check memory usage in Python, you can use the
psutil library for system-wide or process-specific memory info, or memory_profiler to measure memory used by specific functions. These tools provide easy ways to monitor memory consumption during program execution.Syntax
Here are two common ways to check memory usage in Python:
- Using
psutil: Import the library and callpsutil.Process().memory_info()to get memory details of the current process. - Using
memory_profiler: Decorate functions with@profileand run the script withpython -m memory_profiler script.pyto see line-by-line memory usage.
python
import psutil process = psutil.Process() memory_info = process.memory_info() print(memory_info)
Output
pmem(rss=12345678, vms=23456789, shared=3456789, text=456789, lib=0, data=567890, dirty=0)
Example
This example shows how to use psutil to print the current Python process's memory usage in bytes.
python
import psutil import os process = psutil.Process(os.getpid()) memory_info = process.memory_info() print(f"Memory usage: {memory_info.rss} bytes")
Output
Memory usage: 12345678 bytes
Common Pitfalls
Common mistakes when checking memory usage include:
- Not installing required libraries like
psutilormemory_profiler. - Confusing different memory metrics such as RSS (resident set size) and VMS (virtual memory size).
- Expecting memory usage to be exact; it can fluctuate due to system and Python's memory management.
python
import psutil # Wrong: forgetting to get current process memory_info = psutil.memory_info() # This will cause an error # Right: process = psutil.Process() memory_info = process.memory_info() print(memory_info)
Quick Reference
| Method | Description | Usage |
|---|---|---|
| psutil | Get memory info of current process | psutil.Process().memory_info() |
| memory_profiler | Profile memory line-by-line in functions | @profile decorator + run with python -m memory_profiler |
| tracemalloc | Track memory allocations in Python | import tracemalloc; tracemalloc.start() |
Key Takeaways
Use the psutil library to get memory info of the current Python process easily.
memory_profiler helps measure memory usage line-by-line inside functions.
Always install required packages before using them to avoid errors.
Understand different memory terms like RSS and VMS to interpret results correctly.
Memory usage can vary during runtime due to Python and OS behavior.