【发布时间】:2017-12-26 17:47:48
【问题描述】:
目前,我有一些密集 I/O 任务的并行实现。 例如
def func(i):
# Write to i.txt
subprocess.Popen(str(i).txt).wait()
# Another external process to analysis i.txt and generate image i.png
subprocess.Poen(str(i).txt).wait()
# read i.png
color = open("i.png")
return color
pool = ThreadPool(4)
for i in range(1000): # Could be thousands of files
pool.apply_async(func,i)
这两个外部进程要么是 CPU 计算密集型,要么是 GPU 密集型。
与单线程相比,它有显着的加速。 但我仍然想知道是否还有其他优化?可以使用。
IO的顺序可以优化吗?
例如,改为在一个函数中执行三个 I/O,拆分 I/O 使用三个线程队列来避免 wait() 或文件读取。
我是 python 新手,任何建议都会有所帮助。
【问题讨论】:
-
这两个程序能输出到stdout/stdin吗?如果是这样,您始终可以将第一个子进程的输出通过管道传输到第二个子进程,然后从第二个子进程的标准输出中读取(以避免文件系统 I/O)。另外,为什么不只是
pool.map(func, range(1000))? -
一开始你必须修复你的功能,这与预期的工作相去甚远。
标签: python multithreading subprocess