我在从文件中读取图表时遇到了类似的问题 . 处理包括计算不适合存储器的200 000x200 000浮点矩阵(一次一行) . 试使用 gc.collect() 释放计算之间的内存来修复问题的内存相关方面但是它导致性能问题:我不知道为什么但是即使使用的内存量保持不变,每次调用 gc.collect() 的时间也要花费更多时间比前一个 . 很快,垃圾收集占用了大部分的计算时间 .
为了解决内存和性能问题,我转而使用多线程技巧,我曾在某处读过(对不起,我再也找不到相关的帖子) . 在我在一个大的 for 循环中读取文件的每一行之前,处理它,并且每隔一段时间运行 gc.collect() 以释放内存空间 . 现在我调用一个函数来读取和处理新线程中的文件块 . 一旦线程结束,内存将自动释放,而不会出现奇怪的性能问题 .
实际上它的工作原理如下:
from dask import delayed # this module wraps the multithreading
def f(storage, index, chunk_size): # the processing function
# read the chunk of size chunk_size starting at index in the file
# process it using data in storage if needed
# append data needed for further computations to storage
return storage
partial_result = delayed([]) # put into the delayed() the constructor for your data structure
# I personally use

在处理大型浮点矩阵时遇到内存问题,尝试使用`gc.collect()`释放内存但导致性能下降。通过采用多线程策略,使用dask模块读取和处理文件块,每次处理完一个块后内存会自动释放,解决了内存和性能双重问题。
最低0.47元/天 解锁文章

2200

被折叠的 条评论
为什么被折叠?



