Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/meteor/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中使用多线程读取txt文件_Python_Multithreading_Text Files - Fatal编程技术网

在python中使用多线程读取txt文件

在python中使用多线程读取txt文件,python,multithreading,text-files,Python,Multithreading,Text Files,我试图用python读取一个文件(扫描它的行并查找术语)并编写结果——比如说,每个术语的计数器。我需要对大量文件(超过3000个)执行此操作。有可能实现多线程吗?如果是,如何进行 所以,场景是这样的: 读取每个文件并扫描其行 为我读取的所有文件将计数器写入同一输出文件 第二个问题是,它是否提高了读/写速度 希望它足够清楚。谢谢 Ron.是的,应该可以以并行方式执行此操作 然而,在Python中,很难实现多线程并行。出于这个原因,并行处理是更好的默认选择 很难说你能期望达到什么样的加速。这取决

我试图用python读取一个文件(扫描它的行并查找术语)并编写结果——比如说,每个术语的计数器。我需要对大量文件(超过3000个)执行此操作。有可能实现多线程吗?如果是,如何进行

所以,场景是这样的:

  • 读取每个文件并扫描其行
  • 为我读取的所有文件将计数器写入同一输出文件
第二个问题是,它是否提高了读/写速度

希望它足够清楚。谢谢


Ron.

是的,应该可以以并行方式执行此操作


然而,在Python中,很难实现多线程并行。出于这个原因,并行处理是更好的默认选择


很难说你能期望达到什么样的加速。这取决于并行工作负载的哪一部分(越多越好),以及串行工作负载的哪一部分(越少越好)。

我同意@aix的观点,
多处理肯定是一种方法。无论如何,您都将受到i/o限制——无论运行多少并行进程,您的读取速度都是如此之快。但很容易会有一些加速

考虑以下内容(input/是一个目录,其中包含来自Project Gutenberg的几个.txt文件)

当我在双核机器上运行此功能时,会有明显的(但不是2倍)加速:


如果文件足够小,可以放在内存中,并且您有很多未受i/o限制的处理要做,那么您应该会看到更好的改进。

如果您有很多文件,我认为这会创建太多的进程。我得到了这个process.process_files()16.5930001736 process_files_parallel()100.88700084注意,如果您也在那里寻找生成器版本,那么还有pool.imap--对应于python2上的itertools.imap。这是一个很好的例子,顺便说一句,很好的工作。“然而,在Python中,使用多线程很难实现并行性”您能给出原因吗?好答案+1
import os.path
from multiprocessing import Pool
import sys
import time

def process_file(name):
    ''' Process one file: count number of lines and words '''
    linecount=0
    wordcount=0
    with open(name, 'r') as inp:
        for line in inp:
            linecount+=1
            wordcount+=len(line.split(' '))

    return name, linecount, wordcount

def process_files_parallel(arg, dirname, names):
    ''' Process each file in parallel via Poll.map() '''
    pool=Pool()
    results=pool.map(process_file, [os.path.join(dirname, name) for name in names])

def process_files(arg, dirname, names):
    ''' Process each file in via map() '''
    results=map(process_file, [os.path.join(dirname, name) for name in names])

if __name__ == '__main__':
    start=time.time()
    os.path.walk('input/', process_files, None)
    print "process_files()", time.time()-start

    start=time.time()
    os.path.walk('input/', process_files_parallel, None)
    print "process_files_parallel()", time.time()-start
$ python process_files.py
process_files() 1.71218085289
process_files_parallel() 1.28905105591