为什么我的多线程程序很慢?

时间:2017-12-13 14:47:10

标签: python multithreading python-3.x optimization

我试图让我的程序运行得更快,使用线程,但需要花费太多时间。代码必须计算两种矩阵(word_level,其中我比较查询的每两个单词和一个文档,sequence_level:我将查询与文档上的不同序列进行比较。以下是主要函数:

import threading
from threading import Thread

def sim_QxD_word(query, document, model, alpha, outOfVocab, lock): #word_level
    sim_w = {}
    for q in set(query.split()):
        sim_w[q] = {}
        qE = []
        if q in model.vocab:
            qE = model[q]
        elif q in outOfVocab:
            qE = outOfVocab[q]
        else:
            qE = numpy.random.rand(model.layer1_size) # random vector
            lock.acquire()
            outOfVocab[q] = qE
            lock.release()

        for d in set(document.split()):
            dE = []
            if d in model.vocab:
                dE = model[d]
            elif d in outOfVocab:
                dE = outOfVocab[d]
            else:
                dE = numpy.random.rand(model.layer1_size) # random vector
                lock.acquire()
                outOfVocab[d] = dE
                lock.release()
            sim_w[q][d] = sim(qE,dE,alpha)
    return (sim_w, outOfVocab)

def sim_QxD_sequences(query, document, model, outOfVocab, alpha, lock): #sequence_level
    # 1. extract document sequences 
    document_sequences = []
    for i in range(len(document.split())-len(query.split())):
        document_sequences.append(" ".join(document.split()[i:i+len(query.split())]))
    # 2. compute similarities with a query sentence
    lock.acquire()
    query_vec, outOfVocab = avg_sequenceToVec(query, model, outOfVocab, lock)
    lock.release()
    sim_QxD = {}
    for s in document_sequences:
        lock.acquire()
        s_vec, outOfVocab = avg_sequenceToVec(s, model, outOfVocab, lock)
        lock.release()
        sim_QxD[s] = sim(query_vec, s_vec, alpha)
    return (sim_QxD, outOfVocab)

def word_level(q_clean, d_text, model, alpha, outOfVocab, out_w, q, ext_id, lock):
    #print("in word_level")
    sim_w, outOfVocab = sim_QxD_word(q_clean, d_text, model, alpha, outOfVocab, lock)
    numpy.save(join(out_w, str(q)+ext_id+"word_interactions.npy"), sim_w)

def sequence_level(q_clean, d_text, model, outOfVocab, alpha, out_s, q, ext_id, lock):
    #print("in sequence_level")
    sim_s, outOfVocab = sim_QxD_sequences(q_clean, d_text, model, outOfVocab, alpha, lock)
    numpy.save(join(out_s, str(q)+ext_id+"sequence_interactions.npy"), sim_s)

def extract_AllFeatures_parall(q_clean, d_text, model, alpha, outOfVocab, out_w, q, ext_id, out_s, lock):
    #print("in extract_AllFeatures")
    thW=Thread(target = word_level, args=(q_clean, d_text, model, alpha, outOfVocab, out_w, q, ext_id, lock))
    thW.start()
    thS=Thread(target = sequence_level, args=(q_clean, d_text, model, outOfVocab, alpha, out_s, q, ext_id, lock))
    thS.start()
    thW.join()
    thS.join()

def process_documents(documents, index, model, alpha, outOfVocab, out_w, out_s, queries, stemming, stoplist, q):
    #print("in process_documents")
    q_clean = clean(queries[q],stemming, stoplist)
    lock = threading.Lock()
    for d in documents:
        ext_id, d_text = reaDoc(d, index)
        extract_AllFeatures_parall(q_clean, d_text, model, alpha, outOfVocab, out_w, q, ext_id, out_s, lock)

outOfVocab={} # shared variable over all threads
queries = {"1":"first query", ...} # can contain 200 elements

....

threadsList = []
for q in queries.keys():
    thread = Thread(target = process_documents, args=(documents, index, model, alpha, outOfVocab, out_w, out_s, queries, stemming, stoplist, q))
    thread.start()
    threadsList.append(thread)
for th in threadsList:
    th.join()

如何优化不同的功能以使其运行更快? 在此先感谢您的回复。

1 个答案:

答案 0 :(得分:1)

我将在本回答中专注于这些代码行

thread = Thread(target = process_documents(documents, index, model, alpha, outOfVocab, out_w, out_s, queries, stemming, stoplist, q))
thread.start()

来自文档https://docs.python.org/2/library/threading.html

  

target是run()方法调用的可调用对象。   默认为None,表示不调用任何内容。

目标应为可调用。在您的代码中,您传递了对 process_documents 的调用结果。你想要做的是说 target = process_documents (即传入函数本身 - 这是一个可调用的),并根据需要传入args / kwargs。

当您的代码按顺序运行时,对process_documents的每次调用都发生在同一个线程中。您需要为线程提供您希望它执行的工作,而不是作业的结果。