[英]Why does not multithreading speed up my program?
我有一个需要处理的大文本文件。 我首先将所有文本读入一个列表,然后使用 ThreadPoolExecutor 启动多个线程来处理它。 process_text() 中调用的两个函数在这里没有列出:is_channel 和 get_relations()。
我在 Mac 上,我的观察表明它并没有真正加快处理速度(具有 8 个内核的 cpu,只使用了 15% 的 cpu)。 如果 function is_channel 或 get_relations 存在性能瓶颈,那么多线程将无济于事。 这是没有性能提升的原因吗? 我应该尝试使用多处理而不是多线程来加速吗?
def process_file(file_name):
all_lines = []
with open(file_name, 'r', encoding='utf8') as f:
for index, line in enumerate(f):
line = line.strip()
all_lines.append(line)
# Classify text
all_results = []
with ThreadPoolExecutor(max_workers=10) as executor:
for index, result in enumerate(executor.map(process_text, all_lines, itertools.repeat(channel))):
all_results.append(result)
for index, entities_relations_list in enumerate(all_results):
# print out results
def process_text(text, channel):
global channel_text
global non_channel_text
is_right_channel = is_channel(text, channel)
entities = ()
relations = None
entities_relations_list = set()
entities_relations_list.add((entities, relations))
if is_right_channel:
channel_text += 1
entities_relations_list = get_relations(text, channel)
return (text, entities_relations_list, is_right_channel)
non_channel_text += 1
return (text, entities_relations_list, is_right_channel)
应该做的第一件事是找出需要多少时间:
第三点(打印),如果你真的在做,可以减慢速度。 只要您不将其打印到终端并且只是将 output 传送到文件或其他东西,就可以了。
根据时间安排,我们将了解:
x >> y
我的意思是 x 明显大于 y。基于以上和文件大小,您可以尝试几种方法:
即使这可以通过两种方式完成,可以通过再次进行基准测试/查看时间来找出哪种方式更快。
方法 1 (T1 >> T2 甚至当 T1 和 T2 相似时)
queue
而不是列表。以上是单个生产者和多个消费者线程的示例。
方法2 (这只是问题中代码片段已经完成的另一种方式)
(CPU 绑定)
multiprocessing
模块在 python 内完成仅通过查看代码,它似乎受CPU 限制。 因此,我更喜欢多处理来做到这一点。 我在实践中使用了这两种方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.