V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
sunchen
V2EX  ›  问与答

multiprocessing 多进程高速运行一段时间后处理速度急剧变慢

  •  
  •   sunchen · 2017-08-25 15:24:08 +08:00 · 3118 次点击
    这是一个创建于 2428 天前的主题,其中的信息可能已经有所发展或是发生改变。

    multiprocessing 多进程的的方式读取一个目录下的几百万文件, 程序运行的前 10 几秒能快速处理完大约 100W 文件,然后性能急剧下降,每秒中只能处理几百个文件了,百思不得其解啊。 多次运行程序都是会在 100W 左右变慢,机器 64G 内存,8 核 16 线程,机器压力不算大

    代码如下:

    import traceback from multiprocessing import Pool, Queue, Process

    def producer(path): try: with open(path) as f: for line in f: if line.startswith('<title>'): global bug buf.put(u'{0}\t{1}'.format(path, line).encode('utf-8')) break except: traceback.print_exc() print path

    def consumer(buf): with open('baidu_wiki_title.tsv', 'w') as out: while True: try: line = buf.get(timeout=30) out.write(line) except: pass

    def generate(): with open('wiki.txt') as f: count = 0 for line in f: count += 1 if count % 10000==0: print count yield 'wiki/' + line.strip().split()[-1]

    buf = Queue(10000000) p = Process(target=consumer, args=(buf,)) p.start() pool = Pool(100) pool.imap(producer, list(generate())) pool.close() pool.join()

    2 条回复    2017-08-26 14:07:28 +08:00
    peihanw
        1
    peihanw  
       2017-08-26 10:53:54 +08:00
    有可能是磁盘 IO 瓶颈,"iostat -x 5" 看一下,如果%util 接近 100 就说明磁盘 IO 已占满,进程都在等 IO 操作返回。如果是这种情况比较难优化。
    sunchen
        2
    sunchen  
    OP
       2017-08-26 14:07:28 +08:00
    @peihanw 确认是 IO 跟不上,%util 100%, 不太明白问什么刚开始运行的很快,这和文件系统有关系吗? ls 出目标目录下所有文件,顺序访问前 100 万很快,后 20 万也可以,但是中间有部分会很慢。ext4 文件系统
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2497 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 16:08 · PVG 00:08 · LAX 09:08 · JFK 12:08
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.