我正在研究由32亿个字符组成的人类基因组,我有一个需要在这些数据中搜索的对象列表。就像这样:
result_final=[]
objects=['obj1','obj2','obj3',...]
def function(obj):
result_1=search_in_genome(obj)
return(result_1)
for item in objects:
result_2=function(item)
result_final.append(result_2)每个对象在数据中的搜索需要将近30秒,而我有几千个对象。我注意到,在连续地执行此操作时,只使用了7%的CPU和5%的RAM。在我搜索时,为了减少计算时间,我应该使用队列、线程或多处理进行并行计算。但对于非专家来说,它们似乎很复杂。有人能帮助我如何为python编写代码以运行10次同时搜索吗?是否有可能使python使用最大的可用CPU和RAM进行多处理?(我在windows 7上使用Python33,64 GH内存,COREI7和3.5GH CPU)
发布于 2014-07-21 14:04:14
您可以为此使用multiprocessing模块:
from multiprocessing import Pool
objects=['obj1','obj2','obj3',...]
def function(obj):
result_1=search_in_genome(obj)
return(result)
if __name__ == "__main__":
pool = Pool()
result_final = pool.map(function, objects)这将允许您在计算机上的所有可用CPU上扩展工作,因为进程不受GIL的影响。您不会希望运行比CPU可用的任务更多的任务。一旦您这样做,您实际上开始放慢速度,因为随后CPU必须不断地在进程之间切换,这会导致性能损失。
发布于 2014-07-21 12:53:33
好的,我不确定您的问题,但我会这样做(注意,可能有更好的解决方案,因为我不是队列对象方面的专家):
如果要多线程搜索:
class myThread (threading.Thread):
def __init__(self, obj):
threading.Thread.__init__(self)
self.result = None
self.obj = obj
#Function who is called when you start your Thread
def run(self)
#Execute your function here
self.result = search_in_genome(self.obj)
if __name__ == '__main__':
result_final=[]
objects=['obj1','obj2','obj3',...]
#List of Thread
listThread = []
#Count number of potential thread
allThread = objects.len()
allThreadDone = 0
for item in objects:
#Create one thread
thread = myThread(item)
#Launch that Thread
thread.start()
#Stock it into the list
listThread.append(thread)
while True:
for thread in listThread:
#Count number of Thread who are finished
if thread.result != None:
#If a Thread is finished, count it
allThreadDone += 1
#If all thread are finished, then stop program
if allThreadDone == allThread:
break
#Else initialyse flag to count again
else:
allThreadDone = 0如果有人可以检查和验证这段代码,那就更好了。(对我的英语很抱歉)
https://stackoverflow.com/questions/24860331
复制相似问题