Featured image of post 论文写作技巧

论文写作技巧

重度遗忘患者的自救笔记

# 安装 memory_profiler

首先,你需要安装 memory_profiler。可以通过 pip 安装:

1
2
3
4
5
bash


复制
pip install memory-profiler

# 使用 memory_profiler 监控内存:

  1. 你需要在代码中使用 @profile 装饰器来标记你要监控的函数。
  2. 运行时,你可以使用 mprof 工具或直接使用 memory_profiler 来查看内存使用情况。

# 示例代码:

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

@profile
def my_function():
    a = [i for i in range(10**6)]  # 示例:分配大量内存
    b = [i for i in range(10**6)]
    return a, b

if __name__ == "__main__":
    my_function()

# 查看内存使用:

你可以通过以下两种方法之一查看内存使用情况。

# 方法 1:使用命令行工具 mprof

1
2
bash复制mprof run your_script.py  # 运行你的脚本
mprof plot               # 绘制内存使用曲线

# 方法 2:直接在 Python 中运行

如果你直接使用 @profile 装饰器,你可以运行:

1
2
3
4
5
bash


复制
python -m memory_profiler your_script.py

这将输出每个函数的内存使用情况,包括最大内存消耗的详细信息。

# 注意:

  • @profile 装饰器仅适用于 Python 代码中的函数。
  • memory_profiler 是通过跟踪 Python 对象的内存使用来评估内存消耗的,因此它的性能开销可能会略有影响。
Licensed under CC BY-NC-SA 4.0
使用 hugo 构建 🖤 Stack
版权声明:Licensed under CC BY-NC-SA 4.0「署名-非商业性使用-相同方式共享 4.0 国际」