Featured image of post Essay Writing Tips

Essay Writing Tips

Self-help notes for patients with severe amnesia

# Install memory_profiler:

First, you need to install memory_profiler. Can be installed via pip:

1
2
3
4
5
bash


copy
pip install memory-profiler

# Use memory_profiler to monitor memory:

  1. You need to use the @profile decorator in your code to mark the functions you want to monitor.
  2. At runtime, you can use the mprof tool or directly use memory_profiler to view memory usage.

# Sample code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
python copy from memory_profiler import profile

@profile
def my_function():
    a = [i for i in range(10**6)] # Example: allocate a large amount of memory
    b = [i for i in range(10**6)]
    return a, b

if __name__ == "__main__":
    my_function()

# Check memory usage:

You can view memory usage in one of two ways.

# Method 1: Use the command line tool mprof

1
2
bash copy mprof run your_script.py # Run your script
mprof plot # Draw memory usage curve

# Method 2: Run directly in Python

If you use the @profile decorator directly, you can run:

1
2
3
4
5
bash


copy
python -m memory_profiler your_script.py

This will output the memory usage of each function, including details of maximum memory consumption.

# Notice:

  • The @profile decorator only works on functions in Python code.
  • memory_profiler evaluates memory consumption by tracking the memory usage of Python objects, so its performance overhead may be slightly affected.
Licensed under CC BY-NC-SA 4.0
Built with hugo 🖤 Stack
版权声明:Licensed under CC BY-NC-SA 4.0「署名-非商业性使用-相同方式共享 4.0 国际」