如何在 Python 中并行处理列表?

琼·文奇

我写了这样的代码:

def process(data):
   #create file using data

all = ["data1", "data2", "data3"]

我想在我的所有列表上并行执行进程函数,因为它们正在创建小文件,所以我不关心磁盘写入,但处理需要很长时间,所以我想使用我的所有内核。

如何使用 python 2.7 中的默认模块执行此操作?

戈伦

假设 CPython 和GIL在这里。

如果您的任务受 I/O 限制,通常线程处理可能更有效,因为线程只是将工作转储到操作系统上并空闲直到 I/O 操作完成。生成进程是照顾 I/O 的一种繁重方式。

但是,大多数文件系统不是并发的,因此使用多线程或多处理可能不会比同步写入快。

尽管如此,这里有一个人为的示例,multiprocessing.Pool.map它可能有助于您的 CPU 密集型工作:

from multiprocessing import cpu_count, Pool

def process(data):
    # best to do heavy CPU-bound work here...

    # file write for demonstration
    with open("%s.txt" % data, "w") as f:
        f.write(data)

    # example of returning a result to the map
    return data.upper()
      
tasks = ["data1", "data2", "data3"]
pool = Pool(cpu_count() - 1)
print(pool.map(process, tasks))

可以在 中找到类似的线程设置concurrent.futures.ThreadPoolExecutor

all顺便说一句是一个内置函数,不是一个很好的变量名选择。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章