簡體   English   中英

帶有本地字典的Python多線程可加快處理速度

[英]Python multithreading with local dictionary to speed up process

我的進程非常慢,我想使用多線程來加快速度。 我的過程的目標是通讀非常大的數據集並在每一行上進行昂貴的計算,然后將結果存儲在字典中。 我想使用多線程,但不確定如何。 這是我的嘗試。

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from multiprocessing.pool import ThreadPool

def findTweets(side):
     cosine_dict = {}
     for t in tweets:
            topic = [side, t]
            tfidf_vectorizer = TfidfVectorizer()
            topic_matrix = tfidf_vectorizer.fit_transform(topic)
            cosine = cosine_similarity(topic_matrix[0:1], topic_matrix[1:2])
            cosine = float(cosine)
            key = side + "&&" + t
            cosine_dict[key] = cosine
     return cosine_dict

left = [] #just some strings

for l in left:
       pool = ThreadPool(processes = 10)
       result = pool.apply_async(findTweets, (l,))
       cosine_dict_left = result.get()

這似乎並沒有提高性能。 如何在此處應用多線程來加快此過程?

result.get()是一個阻止調用。 因此,您一次只運行一項任務。 一個骯臟的解決辦法是:

left = [] #just some strings
results=[]
pool = ThreadPool(processes = 10)

for l in left:
       results.append(pool.apply_async(findTweets, (l,)))

for result in results:
       cosine_dict_left = result.get()
       #Do something with cosine_dict_left

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM