[英]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.