【问题标题】:Python3.4 memory usagePython3.4内存使用
【发布时间】:2014-11-16 14:22:10
【问题描述】:

考虑这两个代码,我在 python 控制台中运行:

l=[]
for i in range(0,1000): l.append("."*1000000)
# if you check your taskmanager now, python is using nearly 900MB
del l
# now python3 immediately free-d the memory

现在考虑一下:

l=[]
for i in range(0,1000): l.append("."*1000000)
l.append(l)
# if you check your taskmanager now, python is using nearly 900MB
del l
# now python3 won't free the memory

由于我正在使用这些对象,并且我需要将它们从我的内存中释放出来,我需要知道为了让 python 识别它需要删除相应的内存。

PS:我使用的是Windows7。

【问题讨论】:

    标签: python windows-7 garbage-collection python-3.4


    【解决方案1】:

    因为您创建了循环引用,所以在垃圾收集器运行、检测到循环并将其清理之前,不会释放内存。 You can trigger that manually:

    import gc
    gc.collect()  # Memory usage will drop once you run this.
    

    收集器会偶尔自动运行,但前提是certain conditions related to the number of object allocations/deallocations are met:

    gc.set_threshold(threshold0[, threshold1[, threshold2]])

    设置垃圾收集阈值(收集频率)。 将 threshold0 设置为零会禁用收集。

    GC 根据对象的数量将对象分为三代 他们幸存下来的收藏扫描。新对象被放置在 最年轻的一代(第 0 代)。如果一个对象在集合中幸存下来 它被转移到下一代老一代。由于第 2 代是 最老的一代,那一代的对象在一个 收藏。 为了决定何时运行,收集器会跟踪 自上次以来的数字对象分配和释放 收藏。当分配数减去分配数 解除分配超过阈值0,收集开始。

    因此,如果您继续在解释器中创建更多对象,最终垃圾收集器会自行启动。您可以通过降低threshold0 来更频繁地实现这一点,或者您可以在知道您已删除包含引用循环的对象之一时手动调用gc.collect

    【讨论】:

      猜你喜欢
      • 2015-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-04
      • 1970-01-01
      • 1970-01-01
      • 2014-08-25
      相关资源
      最近更新 更多