首页 > 解决方案 > 使用多处理的 Python 并行化函数

问题描述

我是 python 新手并使用 python 2.7。我正在编写一个程序来解析原始 re 文件。我编写了一个函数,它调用一个文件并将每 4 行放入一个列表中。我的文件很大,比如 4 GB 的原始 dna 数据。

def filerd(f):
           identifier = []
           with open(f,'r') as inputfile:
            count = 1
            for line in inputfile:
              if count%4 == 1:
                identifier.append(line)
                count = count + 1
              else:
                count = count + 1
              return identifier

现在我怎样才能并行化这个函数,以便我可以得到加速。有什么办法可以在我的服务器的 5 个核心上运行此功能?

标签: pythonfunctionparallel-processingmultiprocessing

解决方案


正如我在上面的评论中提到的,仅仅通过优化你的功能,你可能会获得很大的速度。我建议尝试以下方法:

import itertools

def filerd(f):
    with open(f, "r") as inputfile:
        return list(itertools.islice(inputfile, None, None, 4))

如果您不需要返回值是一个列表,但可以使用迭代器,则可以删除list(). 然后,最慢的部分很可能是从磁盘加载数据,无论如何您都需要这样做。


推荐阅读