【发布时间】:2015-10-16 12:25:15
【问题描述】:
我有一个python 脚本,它适用于以下方案:读取一个大文件(例如,电影) - 将从中选择的信息组合成一些小的临时文件 - 在子进程中生成一个 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 数量的因素)
【问题讨论】:
-
旁注 - 我总是喜欢使用
multiprocessing和multiprocessing.dummy来轻松测试多处理与多线程问题。它提供了一个简单的 API,并在进程和线程之间轻松切换。 -
你考虑过使用内存映射吗?这会将文件映射到内存中,但在进程之间共享。操作系统会在必要时执行实际的 IO。它还会在不再使用时释放 RAM,即它不会交换。
标签: python multithreading memory io