我有一个 python
脚本,它按以下方案工作:读取一个大文件(例如电影)- 将其中选定的信息组合成许多小的临时文件- 在子进程中生成 a C++
应用程序执行文件处理/计算(分别针对每个文件)- 读取应用程序输出。为了加快脚本速度,我使用了多处理。但是,它有一个主要缺点:每个进程都必须在 RAM 中维护大型输入文件的整个副本,因此当我用完内存时,我只能运行几个进程。因此,由于线程共享地址空间这一事实,我决定改为尝试多线程(或多处理和多线程的某种组合)。由于 python
部分大部分时间使用文件 I/O
或等待 C++
应用程序完成,我认为 GIL
在这里一定不是问题。然而,我观察到性能急剧下降,而不是性能有所提高,这主要是由于 I/O
部分。
我用下面的代码(保存为test.py
)来说明问题:
import sys, threading, tempfile, time
nthreads = int(sys.argv[1])
class IOThread (threading.Thread):
def __init__(self, thread_id, obj):
threading.Thread.__init__(self)
self.thread_id = thread_id
self.obj = obj
def run(self):
run_io(self.thread_id, self.obj)
def gen_object(nlines):
obj = []
for i in range(nlines):
obj.append(str(i) + '\n')
return obj
def run_io(thread_id, obj):
ntasks = 100 // nthreads + (1 if thread_id < 100 % nthreads else 0)
for i in range(ntasks):
tmpfile = tempfile.NamedTemporaryFile('w+')
with open(tmpfile.name, 'w') as ofile:
for elem in obj:
ofile.write(elem)
with open(tmpfile.name, 'r') as ifile:
content = ifile.readlines()
tmpfile.close()
obj = gen_object(100000)
starttime = time.time()
threads = []
for thread_id in range(nthreads):
threads.append(IOThread(thread_id, obj))
threads[thread_id].start()
for thread in threads:
thread.join()
runtime = time.time() - starttime
print('Runtime: {:.2f} s'.format(runtime))
当我用不同数量的线程运行它时,我得到这个:
$ python3 test.py 1
Runtime: 2.84 s
$ python3 test.py 1
Runtime: 2.77 s
$ python3 test.py 1
Runtime: 3.34 s
$ python3 test.py 2
Runtime: 6.54 s
$ python3 test.py 2
Runtime: 6.76 s
$ python3 test.py 2
Runtime: 6.33 s
有人可以向我解释结果并提供一些建议,如何使用多线程有效地并行化 I/O
吗?
编辑:
减速不是由于硬盘性能,因为:
1) 无论如何文件都被缓存到 RAM
2) 多处理(不是多线程)的相同操作确实变得更快(几乎是 CPU 数量的因素)
最佳答案
随着我深入研究这个问题,我对 4 种不同的并行化方法进行了比较基准测试,其中 3 种使用 python
,1 种使用 java
(目的是测试不是比较不同语言之间的 I/O 机制,而是看多线程是否可以提高 I/O 操作)。测试在Ubuntu 14.04.3上进行,所有文件都放在RAM盘上。
虽然数据相当嘈杂,但明显的趋势是显而易见的(见图表;每个条形图 n=5,误差条形图代表 SD):python 多线程未能提高 I/O 性能。最可能的原因是 GIL,因此没有办法解决。
关于python - python 中的多线程 I/O 减慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33170487/