列表理解与生成器表达式之间的内存消耗差异

时间:2017-03-06 08:26:30

标签: python generator list-comprehension

我正在尝试测量使用列表推导创建的列表与使用生成器表达式创建的列表之间的内存差异。

from memory_profiler import profile


@profile
def squares_using_generators():
    for square in (x ** 2 for x in range(200000)):
        if (square % 100000000 == 0):
            print(square)


@profile
def squares_using_list_comprehensions():
    from sys import getsizeof
    l = [x ** 2 for x in range(200000)]
    print('list size {}'.format(getsizeof(l)))
    for square in l:
        if(square % 100000000 == 0):
            print(square)


if __name__=='__main__':
    squares_using_generators()
    squares_using_list_comprehensions()

上述程序的内存配置文件输出如下

squares_using_generators()

Line #    Mem usage    Increment   Line Contents
================================================
     4     37.9 MiB      0.0 MiB   @profile
     5                             def squares_using_generators():
     6     37.9 MiB      0.0 MiB       for square in (x ** 2 for x in range(200000)):
     7     37.9 MiB      0.0 MiB           if (square % 100000000 == 0):
     8     37.9 MiB      0.0 MiB               print(square)

squares_using_list_comprehensions

Line #    Mem usage    Increment   Line Contents
================================================
    11     37.9 MiB      0.0 MiB   @profile
    12                             def squares_using_list_comprehensions():
    13     37.9 MiB      0.0 MiB       from sys import getsizeof
    14     45.1 MiB      7.2 MiB       l = [x ** 2 for x in range(200000)]
    15     45.1 MiB      0.0 MiB       print('list size {}'.format(getsizeof(l)))
    16     45.2 MiB      0.1 MiB       for square in l:
    17     45.2 MiB      0.0 MiB           if(square % 100000000 == 0):
    18     45.2 MiB      0.0 MiB               print(square)

我的程序还会在squares_using_list_comprehensions

的情况下打印列表大小

list size 1671792

我的问题是7.2MiB中两种情况下的记忆差异。为什么不是1671792字节

0 个答案:

没有答案
相关问题