【问题标题】:Python Out of memory in rangePython范围内内存不足
【发布时间】:2014-08-08 15:30:25
【问题描述】:

我有以下问题:

chunks = []

#He we have an out of memory
for i in range(chunks_count):
    chunk_info = {'offset': struct.unpack('<I', stream_file.read(int_length))[0],
                  'length': struct.unpack('<I', stream_file.read(int_length))[0]}
    chunks.append(chunk_info)

上面的代码内存不足,chunk_size 为 2315780096 是很合理的。有没有更好的方法来编写这段代码不耗尽内存?

【问题讨论】:

  • 在 Python 2 中,您可以改用 xrange。在 Python 3 中,range 已经返回了一个类似生成器的对象。还是chunks.append中的内存错误?
  • 什么是chunk_size?你的意思是chunks_count?还是int_length
  • 你有足够的内存来表示 anything 中的 2315780096 个,更不用说数组中的字典了吗?
  • 假设大部分内存用于内容chucks 列表,那你用它做什么呢?

标签: python memory stream


【解决方案1】:

对于 Python 2 来说似乎很可能

chunks = [
    {
        'offset': struct.unpack('<I', stream_file.read(int_length))[0],
        'length': struct.unpack('<I', stream_file.read(int_length))[0]
    }
    for _ in xrange(chunks_count)
]

对于 Python 3,这可能是一个很好的解决方案。

chunks = [
    {
        'offset': struct.unpack('<I', stream_file.read(int_length))[0],
        'length': struct.unpack('<I', stream_file.read(int_length))[0]
    }
    for _ in range(chunks_count)
]

但似乎使用namedtuple 会更好,因为它们比字典更节省内存,并且您的变量表明您可以使用一组固定的字段。

这类似于 Python 2

import collections

ChunkInfo = collections.namedtuple('ChunkInfo', ['offset', 'length'])

chunks = [
    ChunkInfo(
        struct.unpack('<I', stream_file.read(int_length))[0],
        struct.unpack('<I', stream_file.read(int_length))[0])
    )
    for _ in xrange(chunks_count)
]

这适用于 Python 3

import collections

ChunkInfo = collections.namedtuple('ChunkInfo', ['offset', 'length'])

chunks = [
    ChunkInfo(
        struct.unpack('<I', stream_file.read(int_length))[0],
        struct.unpack('<I', stream_file.read(int_length))[0])
    )
    for _ in range(chunks_count)
]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-27
    • 2018-10-31
    • 2013-12-12
    • 2014-10-15
    • 1970-01-01
    相关资源
    最近更新 更多