#
Install memory_profiler:
First, you need to install memory_profiler. Can be installed via pip:
|
|
#
Use memory_profiler to monitor memory:
- You need to use the
@profiledecorator in your code to mark the functions you want to monitor. - At runtime, you can use the
mproftool or directly usememory_profilerto view memory usage.
# Sample code:
|
|
# Check memory usage:
You can view memory usage in one of two ways.
#
Method 1: Use the command line tool mprof
|
|
# Method 2: Run directly in Python
If you use the @profile decorator directly, you can run:
|
|
This will output the memory usage of each function, including details of maximum memory consumption.
# Notice:
- The
@profiledecorator only works on functions in Python code. memory_profilerevaluates memory consumption by tracking the memory usage of Python objects, so its performance overhead may be slightly affected.