Python 了解内存消耗:释放StringIO的内存?
我很好奇为什么在第一个例子中,内存消耗就像我在成像一样:Python 了解内存消耗:释放StringIO的内存?,python,memory,buffer,Python,Memory,Buffer,我很好奇为什么在第一个例子中,内存消耗就像我在成像一样: s = StringIO() s.write('abc'*10000000) # Memory increases: OK s.seek(0) s.truncate() # Memory decreases: OK 在第二个例子中,最后,我使用了相同的方法,但是在使用truncate方法之后,内存似乎没有减少。 以下代码位于类的方法中 from StringIO import StringIO import requests self
s = StringIO()
s.write('abc'*10000000)
# Memory increases: OK
s.seek(0)
s.truncate()
# Memory decreases: OK
在第二个例子中,最后,我使用了相同的方法,但是在使用truncate方法之后,内存似乎没有减少。
以下代码位于类的方法中
from StringIO import StringIO
import requests
self.BUFFER_SIZE = 5 * 1024 * 2 ** 10 # 5 MB
self.MAX_MEMORY = 3 * 1024 * 2 ** 10 # 3 MB
r = requests.get(self.target, stream=True) # stream=True to not download the data at once
chunks = r.iter_content(chunk_size=self.BUFFER_SIZE)
buff = StringIO()
# Get the MAX_MEMORY first data
for chunk in chunks:
buff.write(chunk)
if buff.len > self.MAX_MEMORY:
break
# Left the loop because there is no more chunks: it stays in memory
if buff.len < self.MAX_MEMORY:
self.data = buff.getvalue()
# Otherwise, prepare a temp file and process the remaining chunks
else:
self.path = self._create_tmp_file_path()
with open(self.path, 'w') as f:
# Write the first downloaded data
buff.seek(0)
f.write(buffer.read())
# Free the buffer ?
buff.seek(0)
buff.truncate()
###################
# Memory does not decrease
# And another 5MB will be added to the memory hiting the next line which is normal because it is the size of a chunk
# But if the buffer was freed, the memory would stay steady: - 5 MB + 5 MB
# Write the remaining chunks directly into the file
for chunk in chunks:
f.write(chunk)
从StringIO导入StringIO
导入请求
self.BUFFER_SIZE=5*1024*2**10#5 MB
self.MAX_内存=3*1024*2**10#3 MB
r=requests.get(self.target,stream=True)#stream=True不立即下载数据
chunk=r.iter\u内容(chunk\u size=self.BUFFER\u size)
buff=StringIO()
#首先获取最大内存数据
对于块中的块:
buff.write(块)
如果buff.len>self.MAX_内存:
打破
#离开循环,因为没有更多的块:它保留在内存中
如果buff.len
有什么想法吗?
谢谢。如何衡量“内存增加”?操作系统通常会在释放内存时将内存分配给进程,以防它们再次使用。如何衡量内存使用率?我不是用最好的方法来衡量的,因为我关注的是python进程的内存消耗。但它肯定会增加5Mb,然后在最后一个for循环中再次增加5Mb;gc.collect()-它改变了什么吗?gc.collect没有改变任何东西:/内存仍然加倍。