目前,我有一些密集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使用三个线程队列来避免等待()或文件读取。
我是python的新手,任何建议都会对我有所帮助。
发布于 2017-12-27 02:46:12
好吧,我假设您的进程是链接的,因此不能异步运行。
我建议通过管道传输进程,而不是使用等待。类似于下面的内容
def func(i):
args_write = ['write', '%s.txt' % str(i)]
args_read = ['read', '%s.txt' % str(i)]
args_img = ['color', '%s.png' % str(i)]
# Write to i.txt
process_write = subprocess.Popen(args_write, stdout=subprocess.PIPE, shell=False)
# Another external process to analysis i.txt and generate image i.png
process_read = subprocess.Popen(args_read, stdin=process_write.stdout, stdout=subprocess.PIPE, shell=False)
# read i.png
process_img = subprocess.Popen(args_img, stdin=process_read.stdout, stdout=subprocess.PIPE, shell=False)
process_write.stdout.close()
process_read.stdout.close()
color = process_img.communicate()[0]
return color
pool = ThreadPool(4)
for i in range(1000): # Could be thousands of files
pool.apply_async(func, i)休息看起来不错。
https://stackoverflow.com/questions/47981982
复制相似问题