【问题标题】:multiprocess to split one file - Is it always IO bound?多进程拆分一个文件 - 是否总是 IO 绑定?
【发布时间】:2014-11-04 21:57:52
【问题描述】:

我正在阅读一个类似的线程,其中 OP 希望使用多处理处理函数中的每一行(找到 here)。这个有趣的问题的答案如下:

from multiprocessing import Pool

def process_line(line):
    return "FOO: %s" % line

if __name__ == "__main__":
    pool = Pool(4)
    with open('file.txt') as source_file:
        # chunk the work into batches of 4 lines at a time
        results = pool.map(process_line, source_file, 4)

我想知道您是否可以这样做,但不是返回处理的每一行,而是将其写入另一个文件。

基本上我想看看是否有一种方法可以 MP 读取和写入文件以便按行拆分它。假设我想要每个文件 100,000 行。

from multiprocessing import Pool

def write_lines(line):
    #need method to write lines to multiple files, perhaps a Queue?

if __name__ == "__main__":
    #all my procs
    pool = Pool()
    with open('file.txt') as source_file:
        # chunk the work into batches of 4 lines at a time
        results = pool.map(process_line, source_file, 100000)

我可以使用 MP Queue 将文件拆分为单独的 Queue 对象,然后用写出所有行的作业填充每个处理器,但我仍然必须先通读文件。那么它是否总是完全受 IO 限制而永远无法以有效的方式成为 MP?

【问题讨论】:

    标签: python multithreading io multiprocessing


    【解决方案1】:

    正如您所怀疑的那样,multiprocessing 确实不会对工作负载带来太多好处(如果有的话)。您在这里所做的只是读取一个文件,然后将该文件的内容写入其他文件。这完全是 I/O 绑定的;瓶颈将是读写磁盘的速度。使用multiprocessing 尝试同时将多个文件写入同一个磁盘不会使写入速度更快,因为磁盘一次只能写入一个内容。

    multiprocessing 可以提供帮助的地方是,如果您有一些可以并行化的 CPU 密集型工作,但您正在尝试做的事情实际上并非如此。如果您想从文件中读取行,对每一行进行一些相当繁重的处理,然后然后将它们写入其他文件,multiprocessing 会有所帮助,但听起来你不需要在写每一行之前做任何处理。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-24
      • 2017-06-22
      • 1970-01-01
      • 1970-01-01
      • 2017-02-01
      • 1970-01-01
      相关资源
      最近更新 更多