【问题标题】:python 2 simple for loop high memory usage [duplicate]python 2简单的循环高内存使用[重复]
【发布时间】:2018-01-28 19:49:08
【问题描述】:

使用 Python 2.7 和 3.5 进行测试

for i in range(0, 1000000000):
    pass

当我用 python3 运行这段代码时,一切都很好(小于 3MB 内存使用)

但是python2的内存使用是32GB(我的服务器只有32GB的ram)

如何为 Python 2.7 解决这个问题?

【问题讨论】:

  • 在 Python 3 中,range() 创建一个迭代器,但在 Python 2 中 range() 创建一个列表。在 Python 2 中,请改用 xrange() 创建迭代器。
  • 尝试使用xrange()

标签: python python-2.7 python-3.x memory-management iterator


【解决方案1】:

Python 2.7 中的range 和 Python 3 中的range 是不同的函数。在 Python 3 中,它返回一个迭代器,它一一提供值。在 Python 2.7 中,它返回一个必须为其分配一些内存的数组。可以在Python 2.7版本中使用xrange函数解决。

Python 2.7.12
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> xrange(10)
xrange(10)
>>> iterator = iter(xrange(10))
>>> iterator.next()
0
>>> iterator.next()
1
>>> iterator.next()
2

【讨论】:

    猜你喜欢
    • 2018-04-10
    • 2018-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-15
    • 2020-12-18
    相关资源
    最近更新 更多