You can use the memory_profiler package to profile line-by-line memory usage.
First, install it:
bash
pip install memory-profiler
Then, decorate the function you want to profile:
python
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()
Run the script with:
bash
python -m memory_profiler your_script.py
It will show memory usage line by line.
4. Using time and resource (Linux/macOS only)
You can use the resource module to get maximum memory usage:
python
import resource
# Your code here
usage = resource.getrusage(resource.RUSAGE_SELF)
print(f"Memory usage: {usage.ru_maxrss / 1024:.2f} MB")
Note:
On Linux, ru_maxrss is in kilobytes.
On macOS, it is in bytes.
5. External Tools
You can also monitor memory externally:
Use top, htop, or ps commands in Linux/macOS.
Use Task Manager in Windows.
Example with ps:
bash
ps -o pid,rss,command -p <pid>
Quick Summary
Method
Best for
psutil
Simple snapshot of memory usage
tracemalloc
Tracking memory allocations
memory_profiler
Line-by-line memory profiling
resource
Max memory usage (Linux/macOS)
External tools
Monitoring from outside the script
Would you like me to show you how to plot memory usage over time too? 📈
(It's very useful for long-running scripts!)