python - 使用多处理的 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 个核心上运行此功能?
解决方案
正如我在上面的评论中提到的,仅仅通过优化你的功能,你可能会获得很大的速度。我建议尝试以下方法:
import itertools
def filerd(f):
with open(f, "r") as inputfile:
return list(itertools.islice(inputfile, None, None, 4))
如果您不需要返回值是一个列表,但可以使用迭代器,则可以删除list()
. 然后,最慢的部分很可能是从磁盘加载数据,无论如何您都需要这样做。
推荐阅读
- python - 同时访问列表中所有元素的属性
- javascript - 如何让图像在 HTML 中显示一定次数的 Val
- flutter - 带有 WebView 的溢出容器
- regex - 使用多个括号分组时 sed 没有输出
- laravel - 我可以让用户与每个角色相关联吗 - laravel
- java - Intellij 构建工件 - 可运行的 jar UTF-8
- apache-beam - Apache Bean Spark Runner 在流模式下不起作用 - java.lang.IllegalAccessException
- nuxt.js - 在模块中使用 Nuxt 中的运行时环境变量
- javascript - 如何根据javascript循环中的交互次数创建级联属性?
- javascript - 如何将 Postgres bytea 转换为 base64 字符串