ZetCode

Python memory_profiler

最后修改:2025 年 2 月 15 日

在本文中,我们将展示如何在 Python 中使用 memory_profiler 库。memory_profiler 库用于监控和分析 Python 程序的内存使用情况。它通过提供有关程序执行过程中内存分配和使用的详细报告,帮助开发人员跟踪内存使用情况并识别内存泄漏。

memory_profiler 的主要功能包括:

@profile 装饰器

@profile 装饰器是 memory_profiler 库中的一个工具,用于监控和测量特定函数的内存使用情况。当您将 @profile 装饰器添加到函数时,它会逐行跟踪该函数的内存使用情况,提供有关函数内每行代码之前和之后使用的内存量的详细见解。

mem_prof.py
from memory_profiler import profile

# Define a function to monitor its memory usage
@profile
def allocate_memory(n, count):
    strings = []
    for i in range(count):
        # Create a large string
        large_string = "a" * (n * n)
        strings.append(large_string)
        print(f"String {i+1} of length {n * n} created")
    return strings

# Call the function with larger value and multiple allocations
if __name__ == "__main__":
    allocate_memory(2000, 30)

在此程序中,@profile 装饰器用于监控 allocate_memory 函数的内存使用情况。该函数创建大型字符串并将它们附加到列表中,使我们能够观察内存的分配和释放。

@profile
def allocate_memory(n, count):

@profile 装饰器应用于 allocate_memory 函数以启用内存分析。

large_string = "a" * (n * n)

每次迭代都会创建一个大型字符串,导致内存使用量增加。

$ python -m memory_profiler mem_prof.py

运行示例。

memory_usage 函数

memory_profiler 库中的 memory_usage 函数用于获取进程或特定代码块的当前内存使用情况。它以 MiB(Mebibytes)为单位返回内存使用情况,对于监控程序中的内存消耗非常有用。

main.py
import pandas as pd
import numpy as np
import time
from memory_profiler import memory_usage

def pandas_example():
    # Create a large dataset
    num_rows = 10**7
    df = pd.DataFrame({
        'col1': np.random.randint(0, 100, size=num_rows),
        'col2': np.random.random(size=num_rows),
        'col3': np.random.choice(['A', 'B', 'C', 'D'], size=num_rows)
    })

    # Measure memory usage and time taken for a pandas operation
    start_time = time.time()
    mem_usage = memory_usage((df['col1'].mean, ()))
    end_time = time.time()

    print(f"Pandas Memory Usage: {max(mem_usage)} MB")
    print(f"Pandas Time Taken: {end_time - start_time} seconds")

if __name__ == '__main__':
    pandas_example()

在此程序中,memory_usage 函数用于测量 pandas 操作的内存消耗。该程序创建了一个大型 DataFrame 并计算其一列的平均值。

mem_usage = memory_usage((df['col1'].mean, ()))

memory_usage 函数用于测量 df['col1'].mean 操作的内存使用情况。

print(f"Pandas Memory Usage: {max(mem_usage)} MB")

打印操作期间的最大内存使用量。

$ python main.py
Pandas Memory Usage: 294.81640625 MB
Pandas Time Taken: 6.853306293487549 seconds

来源

Python memory_profiler - 文档

在本文中,我们展示了如何使用 memory_profiler 库来监控和分析 Python 程序的内存使用情况。

作者

我叫 Jan Bodnar,是一位充满热情的程序员,拥有丰富的编程经验。我从 2007 年开始撰写编程文章。至今,我已撰写了 1400 多篇文章和 8 本电子书。我在编程教学方面拥有十多年的经验。

列出所有 Python 教程