memory_profiler
是一个 Python 模块,用于监控和分析 Python 程序的内存使用情况。下面是如何使用 memory_profiler
的基本示例。
安装 memory_profiler
首先,你需要安装 memory_profiler
模块。你可以使用 pip 来安装:
1
| pip install memory_profiler
|
使用示例
以下是一个简单的示例,演示如何使用 memory_profiler
来分析函数的内存使用情况。
示例代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| from memory_profiler import profile import time
@profile def my_function(): a = [1] * (10**6) time.sleep(2) b = [2] * (2 * 10**7) time.sleep(2) del b time.sleep(2) return a
if __name__ == '__main__': my_function()
|
运行示例
保存上面的代码到一个 Python 文件中(例如 memory_test.py
),然后运行该文件:
解释输出
memory_profiler
会生成类似下面的输出:
1 2 3 4 5 6 7 8 9 10 11 12 13
| Filename: memory_test.py
Line # Mem usage Increment Occurrences Line Contents ============================================================= 4 17.4 MiB 17.4 MiB 1 @profile 5 def my_function(): 6 24.6 MiB 7.2 MiB 1 a = [1] * (10**6) 7 24.6 MiB 0.0 MiB 1 time.sleep(2) 8 176.0 MiB 151.4 MiB 1 b = [2] * (2 * 10**7) 9 176.0 MiB 0.0 MiB 1 time.sleep(2) 10 24.6 MiB -151.4 MiB 1 del b 11 24.6 MiB 0.0 MiB 1 time.sleep(2) 12 24.6 MiB 0.0 MiB 1 return a
|
解释
- Mem usage: 内存使用量
- Increment: 内存增量
- Occurrences: 该行代码执行的次数
- Line Contents: 代码行
这个输出显示了每行代码执行前后的内存使用情况,以及每行代码的内存使用增量。这对于识别内存泄漏和优化内存使用非常有用。
实时监控内存使用
除了使用装饰器外,你还可以使用 memory_profiler
进行实时内存使用监控。以下是一个示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| from memory_profiler import memory_usage import time
def my_function(): a = [1] * (10**6) time.sleep(2) b = [2] * (2 * 10**7) time.sleep(2) del b time.sleep(2) return a
if __name__ == '__main__': mem_usage = memory_usage(my_function) print(f"Memory usage over time: {mem_usage}")
|
运行上述代码,会打印出 my_function
执行期间的内存使用情况列表。
这些示例展示了如何使用 memory_profiler
来分析和监控 Python 程序的内存使用。根据你的需求,你可以选择使用装饰器或实时监控方法。