我一直在尝试将包含多行(270 亿)的大文件转换为 JSON。 Google Compute 建议我利用多线程来缩短写入时间。我已经从这个转换了我的代码:import jsonimport progressbarf = open('output.txt', 'r')r = open('json.txt', 'w')import mathnum_permutations = (math.factorial(124)/math.factorial((124-5)))main_bar = progressbar.ProgressBar(maxval=num_permutations, \widgets=[progressbar.Bar('=', '[', ']'), ' ', progressbar.Percentage(), progressbar.AdaptiveETA()])main_bar.start()m = 0for lines in f: x = lines[:-1].split(' ') x = json.dumps(x) x += '\n' r.write(x) m += 1 main_bar.update(m)对此:import jsonimport progressbarfrom Queue import Queueimport threadingq = Queue(maxsize=5)def worker(): while True: task = q.get() r.write(task) q.task_done()for i in range(4): t = threading.Thread(target=worker) t.daemon = True t.start()f = open('output.txt', 'r')r = open('teams.txt', 'w')import mathnum_permutations = (math.factorial(124)/math.factorial((124-5)))main_bar = progressbar.ProgressBar(maxval=num_permutations, \widgets=[progressbar.Bar('=', '[', ']'), ' ', progressbar.Percentage(), progressbar.AdaptiveETA()])main_bar.start()m = 0for lines in f: x = lines[:-1].split(' ') x = json.dumps(x) x += '\n' q.put(x) m += 1 main_bar.update(m)我几乎直接从模块手册中复制了队列编码。以前,整个脚本需要 2 天时间。现在是说20天!我不太确定为什么,有人可以向我解释一下吗? 编辑: 这可以被认为是 Python 全局解释器锁 (GIL) 问题,但是,我不这么认为 - 它不是计算密集型的,并且是一个 IO 瓶颈问题,来自线程文档: 我对此的理解是有限的,但我相信这是后者,即。 IO 绑定(bind)任务。这是我最初想要进行多线程时的最初想法:计算被 IO 调用阻塞,IO 调用可以放入单独的线程以允许计算功能继续。 进一步编辑: 也许事实是我从 INPUT 获得了一个 IO 块,这就是它减慢速度的原因。关于如何有效地将“for”循环发送到单独的线程的任何想法?谢谢! 最佳答案 如果我们删除 progressbar 代码,那么您的代码等效于:#!/usr/bin/env python2import jsonimport sysfor line in sys.stdin: json.dump(line.split(), sys.stdout) # split on any whitespace print为了提高时间性能,你应该先测量它——取一个小的输入文件,这样执行不超过一分钟,然后运行:$ /usr/bin/time ./your-script < output.txt > json.txt我不知道为什么你认为从多个线程将二进制 blob 写入同一个文件应该更快。这里性能瓶颈的候选者是什么: 循环开销(如果线路小且磁盘速度快)。将代码放在函数中(由于用本地替换全局查找,它可能会提高 CPython 的性能) json.dump()(不太可能,但无论如何都要测量它)——使用诸如 ensure_ascii=False 之类的参数并测量结果。尝试其他 json 模块,不同的 Python 实现。 磁盘 I/O -- 将结果文件放在不同的物理磁盘上(运行类似 iotop 、 csysdig 以查看进程如何消耗资源) unicode 字节转换,EOL 转换——以二进制模式打开文件,将 json 文本编码为字节关于Python 多线程 - 写入文件慢 10 倍,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32658667/
10-12 17:48